赞
踩
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
namespace Resource
{
public class RestClient
{
public enum HttpType
{
POST,
DELETE,
PUT,
GET
}
/// <summary>
/// 例如http://www.baidu.com/
/// </summary>
private string BaseUri;
public RestClient(string baseUri)
{
this.BaseUri = baseUri;
}
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
#region Http请求
public string Http<T>(T data, string uri,HttpType httpType, string ecode = "UTF-8", string contentType = "application/json", bool isdeCode = false)
{
return GetData(data, uri, httpType, ecode,contentType,isdeCode);
}
#endregion
#region 基础方法
//创建请求
private HttpWebRequest CreateHttpWebRequest(string uri)
{
try
{
string serviceUrl = string.Format("{0}/{1}", this.BaseUri.TrimEnd('/'), uri.TrimStart('/'));
//创建Web访问对 象
var myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
return myRequest;
}
catch (Exception ex)
{
return null;
}
}
private string GetResponseData(HttpWebRequest webRequest, string ecode = "UTF-8", bool isdeCode = false)
{
try
{
HttpWebResponse myResponse = (HttpWebResponse)webRequest.GetResponse();
//通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding(ecode));
string returnXml = "";
if (!isdeCode)
{
returnXml = reader.ReadToEnd();
}
else
{
returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
}
reader.Close();
myResponse.Close();
return returnXml;
}
catch (Exception ex)
{
return ex.Message;
}
}
private string GetData<T>(T data, string uri, HttpType httpType, string ecode = "UTF-8", string contentType = "application/json", bool isdeCode = false)
{
if (BaseUri.Contains("https"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
}
if (httpType == HttpType.GET)
{
uri = ModelToUriParam(data, uri);
}
var myRequest = CreateHttpWebRequest(uri);
myRequest.Method = httpType.ToString();
myRequest.ContentType = contentType;
//myRequest.MaximumAutomaticRedirections = 1;
// myRequest.AllowAutoRedirect = true;
myRequest.UserAgent = DefaultUserAgent;
// myRequest.ProtocolVersion = HttpVersion.Version10;
// ServicePointManager.ServerCertificateValidationCallback = delegate { return myRequest.Address.AbsoluteUri.Contains("https"); };
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ;
if (httpType != HttpType.GET)
{ //把用户传过来的数据转成“UTF-8”的字节流
byte[] buf = Encoding.GetEncoding(ecode).GetBytes(JsonConvert.SerializeObject(data));
myRequest.ContentLength = buf.Length;
//发送请求
Stream stream = myRequest.GetRequestStream();
stream.Write(buf, 0, buf.Length);
stream.Close();
}
return GetResponseData(myRequest, ecode, isdeCode);
}
/// Model对象转换为uri网址参数形式
/// </summary>
/// <param name="obj">Model对象</param>
/// <param name="url">前部分网址</param>
/// <returns></returns>
private string ModelToUriParam<T>(T obj, string url = "")
{
PropertyInfo[] propertis = obj.GetType().GetProperties();
StringBuilder sb = new StringBuilder();
sb.Append(url);
sb.Append("?");
foreach (var p in propertis)
{
var v = p.GetValue(obj, null);
if (v == null)
continue;
sb.Append(p.Name);
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(v.ToString()));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
#endregion
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。