IcsFromERPJob
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

241 lines
10 KiB

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace ICSSoft.FromERP
{
public class HttpHelper
{
/// <summary>
/// POST请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="requestJson">请求json</param>
/// <param name="token">token</param>
/// <returns></returns>
public static async Task<T> HttpClientPost<T>(string url, string requestJson, Dictionary<string, string> dic=null , string contentType = "application/json", string token = "") where T : new()
{
string result = string.Empty;
Uri postUrl = new Uri(url);
using (HttpContent httpContent = new StringContent(requestJson, System.Text.Encoding.UTF8, contentType))
{
//使用注入的httpclientfactory获取client
using (var httpClient = new HttpClient( ))
{
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
// httpClient.BaseAddress. = HttpVersion.Version10;
// httpClient.DefaultRequestVersion = HttpVersion.Version30,
}
//设置请求头
//设置超时时间
if (!string.IsNullOrEmpty(token))
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
if (dic != null)
{
foreach (var item in dic)
{
httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
httpClient.Timeout = new TimeSpan(0, 0, 60);
HttpResponseMessage res = httpClient.PostAsync(url, httpContent).Result;
res.EnsureSuccessStatusCode();
result = res.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result);
}
}
}
public static async Task<T> HttpClientPost2<T>(string url, string requestJson, Dictionary<string, string> dic, string contentType = "application/json") where T : new()
{
string result = string.Empty;
Uri postUrl = new Uri(url);
//使用注入的httpclientfactory获取client
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
using (StringContent strcontent = new StringContent(requestJson, Encoding.UTF8, contentType))
{
var message = new HttpRequestMessage(HttpMethod.Post, url);
//设置cookie信息
foreach (var item in dic)
{
message.Headers.Add(item.Key, item.Value);
}
//设置contetn
message.Content = strcontent;
//发送请求
var res = httpClient.SendAsync(message).Result;
res.EnsureSuccessStatusCode();
result = await res.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(result);
}
////设置请求头
////设置超时时间
//if (dic != null && dic.Count > 0)
//{
// foreach (var item in dic)
// {
// httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
// }
//}
////if (!string.IsNullOrEmpty(token))
//// httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
//httpClient.Timeout = new TimeSpan(0, 0, 60);
//HttpResponseMessage res = httpClient.PostAsync(url, httpContent).Result;
//res.EnsureSuccessStatusCode();
//result = await res.Content.ReadAsStringAsync();
//return JsonConvert.DeserializeObject<T>(result);
}
}
public static async Task<T> HttpClientGet<T>(string url, string contentType = "application/json", string token = "") where T : new()
{
using (HttpClient httpClient = new HttpClient())
{
if (!string.IsNullOrEmpty(token))
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
httpClient.Timeout = new TimeSpan(0, 0, 60);
HttpResponseMessage res = httpClient.GetAsync(url).Result;
res.EnsureSuccessStatusCode();
var t = res.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(t);
};
}
public static async Task<T> PostForm<T, R>(string Url, R message, Dictionary<string, string> dic=null) where T : new()
{
var res = new T();
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var body = new List<KeyValuePair<string, string>>();
foreach (PropertyInfo info in typeof(R).GetProperties())
{
var entity = new KeyValuePair<string, string>(info.Name, info.GetValue(message).ToString());
body.Add(entity);
}
var content = new FormUrlEncodedContent(body);
httpClient.DefaultRequestHeaders.Add("Method", "Post");
if (dic != null)
{
foreach (var item in dic)
{
httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
HttpResponseMessage response = httpClient.PostAsync(Url, content).Result;
if ((int)response.StatusCode == 200)
{
response.EnsureSuccessStatusCode();
}
string result = response.Content.ReadAsStringAsync().Result;
res = JsonConvert.DeserializeObject<T>(result);
}
return res;
}
public static async Task<T> HttpPostNoFile<T>(string url, string data)
{
// Encoding encoding = Encoding.UTF8;
// string jsonParam = data;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "post";
request.ContentType = "application/json";
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var result= reader.ReadToEnd().ToString();
return JsonConvert.DeserializeObject<T>(result);
}
}
}
public static string PostData(byte[] data, string url, string contentType = "application/json", int timeout = 20)
{
//创建httpWebRequest对象
HttpWebRequest httpRequest = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
httpRequest = WebRequest.Create(url) as HttpWebRequest;
httpRequest.ProtocolVersion = HttpVersion.Version10;
}
else
{
httpRequest = WebRequest.Create(url) as HttpWebRequest;
}
if (httpRequest == null)
{
throw new ApplicationException(string.Format("Invalid url string: {0}", url));
}
//填充httpWebRequest的基本信息
httpRequest.ContentType = contentType;
httpRequest.Method = "POST";
httpRequest.Timeout = timeout * 1000;
//填充并发送要post的内容
httpRequest.ContentLength = data.Length;
httpRequest.Headers.Add("deipaaskeyauth", "a5P1RTL4380zd9jpb57qXx63rdynUHN2");
using (Stream requestStream = httpRequest.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
//发送post请求到服务器并读取服务器返回信息
var response = httpRequest.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
//读取服务器返回信息
string stringResponse = string.Empty;
using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
{
stringResponse = responseReader.ReadToEnd();
}
responseStream.Close();
return stringResponse;
}
}
}
}