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
{
///
/// POST请求
///
/// 地址
/// 请求json
/// token
///
public static async Task HttpClientPost(string url, string requestJson, Dictionary 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;
}
//设置请求头
//设置超时时间
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, 10, 0);
HttpResponseMessage res = httpClient.PostAsync(url, httpContent).Result;
res.EnsureSuccessStatusCode();
result = res.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject(result);
}
}
}
public static async Task HttpClientGet(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);
};
}
public static async Task PostForm(string url, R message, Dictionary dic=null) where T : new()
{
var res = new T();
using (HttpClient 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,
}
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var body = new List>();
foreach (PropertyInfo info in typeof(R).GetProperties())
{
var entity = new KeyValuePair(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);
}
}
httpClient.Timeout = new TimeSpan(0, 2, 0);
HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
if ((int)response.StatusCode == 200)
{
response.EnsureSuccessStatusCode();
}
string result = response.Content.ReadAsStringAsync().Result;
res = JsonConvert.DeserializeObject(result);
}
return res;
}
public static async Task HttpPostNoFile(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(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;
}
}
}
}