You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
AUCMA_SCADA/Admin.Core.Socket/Helper/HttpRequestUtility.cs

303 lines
11 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Admin.Core.Socket.Helper
{
public class HttpRequestUtility
{
/// <summary>
/// The default user agent
/// </summary>
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 CookieCollection cookieCollection = new CookieCollection();
#region Post方式请求URL并返回T类型
/// <summary>
/// Post方式请求URL并返回T类型
/// </summary>
/// <typeparam name="T">接收JSON的数据类型</typeparam>
/// <param name="url">传入的url</param>
/// <returns>传入的对象</returns>
public static T PostJson<T>(string url, string data, string token, string flag)
{
// JavaScriptSerializer js = new JavaScriptSerializer();
string returnText = Post(url, data, token, flag);//使用get获取
//T result = js.Deserialize<T>(returnText);
T result = JsonConvert.DeserializeObject<T>(returnText);
return result;
}
#endregion
#region Post发送请求
/// <summary>
/// Post发送请求
/// </summary>
/// <param name="url">请求的url</param>
/// <param name="data">请求的数据</param>
/// <param name="token">安全token</param>
/// <param name="flag">标识login登陆userrToken:获取用户、设备数据</param>
/// <returns>返回值</returns>
public static string Post(string url, string data, string token, string flag)
{
string result = string.Empty;
try
{
var response = PostHttpResponse(url, data, token, 50000, DefaultUserAgent, flag, Encoding.UTF8, cookieCollection);
var stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
result = reader.ReadToEnd();
stream.Close();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
#endregion
#region 创建Post方式的HTTP请求
public static HttpWebResponse PostHttpResponse(string url, string content, string token, int? timeout, string userAgent, string flag, Encoding requestEncoding, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
//获取token使用
if (flag == "login")
{
SetHeaderValue(request.Headers, "X-Requested-With", "XMLHttpRequest");
SetHeaderValue(request.Headers, "Content-type", "application/json");
}
if (flag == "user" || flag == "rtoken")
{
SetHeaderValue(request.Headers, "Authorization", "Bearer " + token);//刷新的token
}
if (flag == "Authorization")
{
SetHeaderValue(request.Headers, "Content-type", "application/json");
SetHeaderValue(request.Headers, "Authorization", "Bearer " + token);
}
if (flag == "userInfo")
{
SetHeaderValue(request.Headers, "Content-type", "application/json");
SetHeaderValue(request.Headers, "UserName", "admin");
SetHeaderValue(request.Headers, "Password", "ZmVuZ3RhaXpoYW4xMjM=");
}
if (flag == "zhiwucloud")
{
SetHeaderValue(request.Headers, "Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
SetHeaderValue(request.Headers, "Authorization", "Basic MGUyZjNjN2RlMjRkNzkxYTA3MDY1NmI2NzhiMTBiMWUwYzg4NDg4MzphZGJlZmYxYjUyNjliMDE1YzBmYzZiNDJlZjhkZjQwN2ZkNjlhNmIw");
}
if (flag == "hnt")
{
SetHeaderValue(request.Headers, "Content-type", "application/json;charset=UTF-8");
}
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//如果需要POST数据
byte[] data = requestEncoding.GetBytes(content);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
return request.GetResponse() as HttpWebResponse;
}
#endregion
#region 往head头部加信息
// <summary>
/// 往head头部加信息
/// </summary>
/// <param name="header"></param>
/// <param name="name"></param>
/// <param name="value"></param>
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
if (property != null)
{
var collection = property.GetValue(header, null) as NameValueCollection;
collection[name] = value;
}
}
#endregion
#region Checks the validation result.
/// <summary>
/// Checks the validation result.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="chain">The chain.</param>
/// <param name="errors">The errors.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
#endregion
#region Get方式请求URL并返回T类型
/// <summary>
/// GET方式请求URL并返回T类型
/// </summary>
/// <typeparam name="T">接收JSON的数据类型</typeparam>
/// <param name="url">传入的url</param>
/// <param name="encoding"></param>
/// <param name="maxJsonLength">允许最大JSON长度</param>
/// <returns>传入的对象</returns>
public static T GetJson<T>(string url, string token, string flag)
{
// JavaScriptSerializer js = new JavaScriptSerializer();
string returnText = Get(url, token, flag);//使用get获取
// T result = js.Deserialize<T>(returnText);
string rt = returnText.Replace("params", "param");
T result = JsonConvert.DeserializeObject<T>(rt);
return result;
}
#endregion
#region Get发送请求
/// <summary>
/// Post发送请求
/// </summary>
/// <param name="url">请求的url</param>
/// <param name="data">请求的数据</param>
/// <param name="token">安全token</param>
/// <param name="flag">标识login登陆userrToken:获取用户、设备数据</param>
/// <returns>返回值</returns>
public static string Get(string url, string token, string flag)
{
string result = string.Empty;
try
{
var response = GetHttpResponse(url, token, 50000, DefaultUserAgent, flag, Encoding.UTF8, cookieCollection);
using (var stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
result = reader.ReadToEnd();
stream.Close();
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
#endregion
#region 创建Get方式的HTTP请求
public static HttpWebResponse GetHttpResponse(string url, string token, int? timeout, string userAgent, string flag, Encoding requestEncoding, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "GET";
//获取token使用
if (flag == "user" || flag == "rtoken")
{
SetHeaderValue(request.Headers, "Authorization", "Bearer " + token);//刷新的token
}
if (flag == "zhiwucloud")
{
SetHeaderValue(request.Headers, "Content-type", "application/json");
//SetHeaderValue(request.Headers, "Authorization", "Basic MGUyZjNjN2RlMjRkNzkxYTA3MDY1NmI2NzhiMTBiMWUwYzg4NDg4MzphZGJlZmYxYjUyNjliMDE1YzBmYzZiNDJlZjhkZjQwN2ZkNjlhNmIw");
}
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}
#endregion
}
}