388 lines
13 KiB
C#
388 lines
13 KiB
C#
using JSMachine.DCS.Infrastructure;
|
|
using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
|
using RestSharp;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Security;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Web;
|
|
|
|
namespace JSMachine.WMS.Infrastructure.Helper
|
|
{
|
|
public static class HttpRequestHelper
|
|
{
|
|
/// <summary>
|
|
/// 字典方式请求,支持表单数据
|
|
/// </summary>
|
|
/// <param name="url"></param>
|
|
/// <param name="method"></param>
|
|
/// <param name="dic"></param>
|
|
/// <param name="postFileParam"></param>
|
|
/// <param name="timeOut"></param>
|
|
/// <returns></returns>
|
|
public async static Task<string> RequestByDic(string url,
|
|
Method method,
|
|
Dictionary<string, object> dic = null,
|
|
List<PostFileParam> postFileParam = null,
|
|
int timeOut = 5000)
|
|
{
|
|
|
|
RestClient client = new(url)
|
|
{
|
|
Timeout = timeOut
|
|
};
|
|
|
|
RestRequest request = new(method);
|
|
|
|
dic?.Select(p => p.Key)
|
|
.ToList()
|
|
.ForEach(key => request.AddParameter(key, dic[key]));
|
|
|
|
postFileParam?.ForEach(p =>
|
|
{
|
|
request.AddFile(p.RemoteParamName, p.FileBytes, p.FileName);
|
|
});
|
|
|
|
IRestResponse response = await client.ExecuteAsync(request);
|
|
|
|
if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null)
|
|
return response.Content;
|
|
|
|
if (response.ErrorException != null)
|
|
{
|
|
LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}");
|
|
LogHelper.Error("当前请求url:" + url);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON参数请求
|
|
/// </summary>
|
|
/// <param name="url"></param>
|
|
/// <param name="method"></param>
|
|
/// <param name="json"></param>
|
|
/// <param name="timeOut"></param>
|
|
/// <returns></returns>
|
|
public async static Task<string> RequestByJson(string url, Method method, string json, int timeOut = 5000)
|
|
{
|
|
RestClient client = new(url)
|
|
{
|
|
Timeout = timeOut
|
|
};
|
|
RestRequest request = new(method);
|
|
|
|
request.AddHeader("Content-Type", "application/json");
|
|
request.AddParameter("application/json", json, ParameterType.RequestBody);
|
|
IRestResponse response = client.Execute(request);
|
|
|
|
if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null)
|
|
return response.Content;
|
|
|
|
if (response.ErrorException != null)
|
|
{
|
|
LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}");
|
|
LogHelper.Error("当前请求url:" + url);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON参数请求
|
|
/// </summary>
|
|
/// <param name="url"></param>
|
|
/// <param name="method"></param>
|
|
/// <param name="json"></param>
|
|
/// <param name="token"></param>
|
|
/// <param name="timeOut"></param>
|
|
/// <returns></returns>
|
|
public async static Task<string> RequestByJson(string url, Method method, string json, string token, int timeOut = 5000)
|
|
{
|
|
|
|
RestClient client = new(url)
|
|
{
|
|
Timeout = timeOut
|
|
};
|
|
RestRequest request = new(method);
|
|
|
|
request.AddHeader("Authorization", $"Bearer {token}");
|
|
request.AddHeader("Content-Type", "application/json");
|
|
|
|
request.AddHeader("Content-Type", "application/json");
|
|
request.AddParameter("application/json", json, ParameterType.RequestBody);
|
|
IRestResponse response = await client.ExecuteAsync(request);
|
|
|
|
if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null)
|
|
return response.Content;
|
|
|
|
if (response.ErrorException != null)
|
|
{
|
|
LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}");
|
|
LogHelper.Error("当前请求url:" + url);
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// 无参请求返回二进制(用于下载文件)
|
|
/// </summary>
|
|
/// <param name="url"></param>
|
|
/// <param name="method"></param>
|
|
/// <param name="timeOut"></param>
|
|
/// <returns></returns>
|
|
public async static Task<byte[]> RequestRturnRawAsync(string url, Method method, int timeOut = 5000)
|
|
{
|
|
if (string.IsNullOrEmpty(url))
|
|
return null;
|
|
|
|
RestClient client = new(url)
|
|
{
|
|
Timeout = timeOut
|
|
};
|
|
|
|
RestRequest request = new(method);
|
|
request.AlwaysMultipartFormData = true;
|
|
|
|
|
|
IRestResponse response = await client.ExecuteAsync(request);
|
|
|
|
if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null)
|
|
return response.RawBytes;
|
|
|
|
if (response.ErrorException != null)
|
|
{
|
|
LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}");
|
|
LogHelper.Error("当前请求url:" + url);
|
|
}
|
|
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 无参请求返回二进制(用于下载文件)
|
|
/// </summary>
|
|
/// <param name="url"></param>
|
|
/// <param name="method"></param>
|
|
/// <param name="timeOut"></param>
|
|
/// <returns></returns>
|
|
public static byte[] RequestRturnRaw(string url, Method method, int timeOut = 5000)
|
|
{
|
|
if (string.IsNullOrEmpty(url))
|
|
return null;
|
|
|
|
RestClient client = new(url)
|
|
{
|
|
Timeout = timeOut
|
|
};
|
|
|
|
RestRequest request = new(method);
|
|
request.AlwaysMultipartFormData = true;
|
|
|
|
IRestResponse response = client.Execute(request);
|
|
|
|
if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null)
|
|
return response.RawBytes;
|
|
|
|
if (response.ErrorException != null)
|
|
{
|
|
LogHelper.Error($"HttpRequstHandling.PostFile--{response.ErrorException.Message}");
|
|
LogHelper.Error("当前请求url:" + url);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取请求的数据
|
|
/// </summary>
|
|
private static string GetResponseString(WebResponse webResponse)
|
|
{
|
|
using (var stream = webResponse.GetResponseStream())
|
|
{
|
|
if (stream == null) return string.Empty;
|
|
using (var reader = new StreamReader(stream, Encoding.UTF8))
|
|
{
|
|
return reader.ReadToEnd();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 以GET方式请求HTTP地址并获取返回
|
|
/// </summary>
|
|
public async static Task<string> Get(string url, Dictionary<string, string> headers = null,
|
|
CookieCollection cookies = null)
|
|
{
|
|
HttpWebRequest request = null;
|
|
WebResponse response = null;
|
|
try
|
|
{
|
|
ServicePointManager.DefaultConnectionLimit = 200;
|
|
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
//对服务端证书进行有效性校验
|
|
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
|
|
}
|
|
request = (HttpWebRequest)WebRequest.Create(url);
|
|
request.Method = "GET";
|
|
|
|
if (headers != null && headers.Count > 0)
|
|
{
|
|
foreach (var header in headers)
|
|
{
|
|
request.Headers.Add(header.Key, header.Value);
|
|
}
|
|
}
|
|
|
|
if (cookies != null)
|
|
{
|
|
request.CookieContainer = new CookieContainer();
|
|
request.CookieContainer.Add(cookies);
|
|
}
|
|
response = request.GetResponse();
|
|
return GetResponseString(response);
|
|
}
|
|
catch (System.Threading.ThreadAbortException e)
|
|
{
|
|
System.Threading.Thread.ResetAbort();
|
|
throw new Exception(e.Message);
|
|
}
|
|
finally
|
|
{
|
|
request?.Abort();
|
|
response?.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 以POST方式请求HTTP地址并获取返回
|
|
/// </summary>
|
|
/// <param name="url">HTTP地址</param>
|
|
/// <param name="parameters">POST的键值对参数</param>
|
|
/// <param name="headers"></param>
|
|
/// <param name="cookies"></param>
|
|
/// <returns></returns>
|
|
public async static Task<string> Post(string url, Dictionary<string, string> parameters,
|
|
Dictionary<string, string> headers = null, CookieCollection cookies = null)
|
|
{
|
|
return await Post(url, GetPostData(parameters), null, headers, cookies);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 以POST方式请求HTTP地址并获取返回
|
|
/// </summary>
|
|
/// <param name="url">HTTP地址</param>
|
|
/// <param name="content">POST的内容</param>
|
|
/// <param name="contentType"></param>
|
|
/// <param name="headers"></param>
|
|
/// <param name="cookies"></param>
|
|
/// <returns></returns>
|
|
public async static Task<string> Post(string url, string content, string contentType = null,
|
|
Dictionary<string, string> headers = null, CookieCollection cookies = null)
|
|
{
|
|
HttpWebRequest request = null;
|
|
HttpWebResponse response = null;
|
|
|
|
try
|
|
{
|
|
ServicePointManager.DefaultConnectionLimit = 200;
|
|
//如果是发送HTTPS请求
|
|
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
//对服务端证书进行有效性校验
|
|
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
|
|
}
|
|
request = (HttpWebRequest)WebRequest.Create(url);
|
|
request.Method = "POST";
|
|
request.Timeout = 30000;
|
|
request.ContentType = contentType ?? "application/x-www-form-urlencoded";
|
|
|
|
if (headers != null && headers.Count > 0)
|
|
{
|
|
foreach (var header in headers)
|
|
{
|
|
request.Headers.Add(header.Key, header.Value);
|
|
}
|
|
}
|
|
|
|
if (cookies != null)
|
|
{
|
|
request.CookieContainer = new CookieContainer();
|
|
request.CookieContainer.Add(cookies);
|
|
}
|
|
//发送POST数据
|
|
var data = Encoding.UTF8.GetBytes(content ?? string.Empty);
|
|
request.ContentLength = data.Length;
|
|
using (var stream = request.GetRequestStream())
|
|
{
|
|
stream.Write(data, 0, data.Length);
|
|
}
|
|
|
|
response = (HttpWebResponse)request.GetResponse();
|
|
return GetResponseString(response);
|
|
}
|
|
catch (System.Threading.ThreadAbortException e)
|
|
{
|
|
System.Threading.Thread.ResetAbort();
|
|
throw new Exception(e.Message);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
throw new Exception(e.Message);
|
|
}
|
|
finally
|
|
{
|
|
request?.Abort();
|
|
response?.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 字典转化为post数据
|
|
/// </summary>
|
|
/// <param name="dictionary"></param>
|
|
/// <returns></returns>
|
|
private static string GetPostData(Dictionary<string, string> dictionary)
|
|
{
|
|
if (dictionary == null || dictionary.Count == 0) return string.Empty;
|
|
var sb = new StringBuilder();
|
|
var keys = dictionary.Keys.ToList();
|
|
for (var i = 0; i < keys.Count; i++)
|
|
{
|
|
if (i > 0)
|
|
{
|
|
sb.Append("&");
|
|
}
|
|
sb.AppendFormat("{0}={1}", keys[i], HttpUtility.UrlEncode(dictionary[keys[i]]));
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 验证证书
|
|
/// </summary>
|
|
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
|
|
SslPolicyErrors errors)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
public class PostFileParam
|
|
{
|
|
public string RemoteParamName { get; set; }
|
|
public string FileName { get; set; }
|
|
public byte[] FileBytes { get; set; }
|
|
}
|
|
}
|