278 lines
11 KiB
C#
278 lines
11 KiB
C#
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Serialization;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Net;
|
||
using System.Net.Security;
|
||
using System.Security.Cryptography.X509Certificates;
|
||
using System.Text;
|
||
|
||
namespace ToolLibrary
|
||
{
|
||
public class HttpHelper
|
||
{
|
||
/// <summary>
|
||
/// http请求,POST方式
|
||
/// </summary>
|
||
/// <param name="url">请求连接</param>
|
||
/// <param name="dicParams">请求参数</param>
|
||
/// <returns>根据泛型返回响应值</returns>
|
||
public static T HttpPostRequest<T>(string url, object dicParams, string accessToken = null)
|
||
{
|
||
Stream requestStream = null;
|
||
try
|
||
{
|
||
Encoding encoding = Encoding.UTF8;
|
||
HttpWebRequest request = GetHttpWebRequest(url);
|
||
request.Method = "POST";
|
||
request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
|
||
request.ContentType = "application/json;charset=UTF-8";
|
||
//request.Headers.Add("ContentType", "application/json; charset=utf-8");
|
||
if (!string.IsNullOrEmpty(accessToken))
|
||
request.Headers.Add("Authorization", "Bearer" + " " + accessToken);
|
||
if (dicParams != null)
|
||
{
|
||
var paramStr = ObjectToJsonStr(dicParams);
|
||
byte[] buffer = encoding.GetBytes(paramStr);
|
||
request.ContentLength = buffer.Length;
|
||
requestStream = request.GetRequestStream();
|
||
requestStream.Write(buffer, 0, buffer.Length);
|
||
}
|
||
return GetResponseValue<T>(request);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
finally
|
||
{
|
||
if (requestStream != null)
|
||
requestStream.Close();
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// http请求,POST方式,文件断点续传
|
||
/// </summary>
|
||
/// <param name="url">请求连接</param>
|
||
/// <param name="dicParams">请求参数</param>
|
||
/// <returns>根据泛型返回响应值</returns>
|
||
public static T HttpPostRequest<T>(string url, byte[] buffer, string contentRange = null, string accessToken = null)
|
||
{
|
||
try
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
|
||
request.Method = "POST";
|
||
//request.Accept = "text/html, application/xhtml+xml, */*"; //"text/html, application/xhtml+xml, */*";
|
||
request.ContentType = "multipart/form-data";
|
||
if (!string.IsNullOrWhiteSpace(contentRange))
|
||
request.Headers.Add("Content-Range", contentRange);
|
||
if (!string.IsNullOrEmpty(accessToken))
|
||
request.Headers.Add("Authorization", "Bearer" + " " + accessToken);
|
||
if (buffer != null)
|
||
{
|
||
request.ContentLength = buffer.Length;
|
||
request.GetRequestStream().Write(buffer, 0, buffer.Length);
|
||
}
|
||
return GetResponseValue<T>(request);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
public static T HttpPostFileRequest<T>(string url, string boundary, MemoryStream memoryStream, string accessToken = null)
|
||
{
|
||
if (memoryStream == null) return default(T);
|
||
Stream requestStream = null;
|
||
try
|
||
{
|
||
HttpWebRequest request = GetHttpWebRequest(url);
|
||
|
||
request.Method = "POST";
|
||
request.ContentType = "multipart/form-data;boundary=" + boundary;
|
||
if (!string.IsNullOrEmpty(accessToken))
|
||
request.Headers.Add("Authorization", "Bearer" + " " + accessToken);
|
||
request.ContentLength = memoryStream.Length;
|
||
request.KeepAlive = true;
|
||
request.Credentials = CredentialCache.DefaultCredentials;
|
||
memoryStream.Position = 0;
|
||
byte[] buffer = new byte[memoryStream.Length];
|
||
memoryStream.Read(buffer, 0, buffer.Length);
|
||
requestStream = request.GetRequestStream();
|
||
requestStream.Write(buffer, 0, buffer.Length);
|
||
return GetResponseValue<T>(request);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
finally
|
||
{
|
||
memoryStream.Close();
|
||
if (requestStream != null)
|
||
requestStream.Close();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// http请求,POST方式,不需要返回值
|
||
/// </summary>
|
||
/// <param name="url">请求连接</param>
|
||
/// <param name="dicParams">请求参数</param>
|
||
public static void HttpPostRequest(string url, object dicParams)
|
||
{
|
||
try
|
||
{
|
||
Encoding encoding = Encoding.UTF8;
|
||
HttpWebRequest request = GetHttpWebRequest(url);
|
||
request.Method = "POST";
|
||
request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
|
||
request.ContentType = "application/json";
|
||
if (dicParams != null)
|
||
{
|
||
byte[] buffer = encoding.GetBytes(ObjectToJsonStr(dicParams));
|
||
request.ContentLength = buffer.Length;
|
||
var requestStream = request.GetRequestStream();
|
||
requestStream.Write(buffer, 0, buffer.Length);
|
||
requestStream.Close();
|
||
}
|
||
request.GetResponse();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// http请求,GET方式
|
||
/// </summary>
|
||
/// <param name="url">请求连接</param>
|
||
/// <param name="dicParams">请求参数</param>
|
||
/// <returns>根据泛型返回响应值</returns>
|
||
public static T HttpGetRequest<T>(string url, Dictionary<string, string> dicParams = null, string accessToken = null)
|
||
{
|
||
try
|
||
{
|
||
StringBuilder sBuilder = new StringBuilder();
|
||
sBuilder.Append(url);
|
||
if (dicParams != null && dicParams.Count > 0)
|
||
{
|
||
sBuilder.Append("?");
|
||
int i = 0;
|
||
foreach (KeyValuePair<string, string> pair in dicParams)
|
||
{
|
||
if (i > 0)
|
||
sBuilder.Append("&");
|
||
sBuilder.AppendFormat("{0}={1}", pair.Key, pair.Value);
|
||
i++;
|
||
}
|
||
}
|
||
HttpWebRequest request = GetHttpWebRequest(url);
|
||
request.Method = "GET";
|
||
request.Accept = "application/json, text/javascript, */*";
|
||
if (!string.IsNullOrEmpty(accessToken))
|
||
request.Headers.Add("Authorization", "Bearer" + " " + accessToken);
|
||
|
||
return GetResponseValue<T>(request);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// http请求,GET方式,不需要返回值
|
||
/// </summary>
|
||
/// <param name="url">请求连接</param>
|
||
/// <param name="dicParams">请求参数</param>
|
||
/// <returns>根据泛型返回响应值</returns>
|
||
public static void HttpGetRequest(string url, Dictionary<string, string> dicParams = null)
|
||
{
|
||
try
|
||
{
|
||
StringBuilder sBuilder = new StringBuilder();
|
||
sBuilder.Append(url);
|
||
if (dicParams != null && dicParams.Count > 0)
|
||
{
|
||
sBuilder.Append("?");
|
||
int i = 0;
|
||
foreach (KeyValuePair<string, string> pair in dicParams)
|
||
{
|
||
if (i > 0)
|
||
sBuilder.Append("&");
|
||
sBuilder.AppendFormat("{0}={1}", pair.Key, pair.Value);
|
||
i++;
|
||
}
|
||
}
|
||
HttpWebRequest request = GetHttpWebRequest(url);
|
||
request.Method = "GET";
|
||
request.GetResponse();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
|
||
private static T GetResponseValue<T>(HttpWebRequest request)
|
||
{
|
||
HttpWebResponse response = null;
|
||
try
|
||
{
|
||
T rstObj = default(T);
|
||
response = (HttpWebResponse)request.GetResponse();
|
||
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
|
||
{
|
||
string rstStr = reader.ReadToEnd();
|
||
rstObj = JsonConvert.DeserializeObject<T>(rstStr);
|
||
reader.Close();
|
||
reader.Dispose();
|
||
}
|
||
return rstObj;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
finally
|
||
{
|
||
if (response != null)
|
||
response.Close();
|
||
}
|
||
}
|
||
|
||
private static HttpWebRequest GetHttpWebRequest(string url)
|
||
{
|
||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
|
||
if (url.ToLower().Trim().StartsWith("https"))
|
||
{
|
||
request.ProtocolVersion = HttpVersion.Version10;
|
||
//在每个HttpWebRequest实例上设置ServerCertificateValidationCallback属性
|
||
request.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
|
||
//ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
|
||
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
|
||
}
|
||
//request.Timeout = 10000;
|
||
return request;
|
||
}
|
||
|
||
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
|
||
{
|
||
return true; //总是接受
|
||
}
|
||
|
||
private static string ObjectToJsonStr(object obj)
|
||
{
|
||
if (obj == null) return "";
|
||
var serializerSettings = new JsonSerializerSettings
|
||
{
|
||
// 设置为驼峰命名
|
||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||
};
|
||
return JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings);
|
||
}
|
||
}
|
||
} |