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;
namespace ICSSoft.FromERP
{
public class HttpHelper
{
///
/// POST请求
///
/// 地址
/// 请求json
/// token
///
public static async Task HttpClientPost(string url, string requestJson, 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 (!string.IsNullOrEmpty(token))
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
httpClient.Timeout = new TimeSpan(0, 0, 60);
var res = httpClient.PostAsync(url, httpContent).Result;
res.EnsureSuccessStatusCode();
result = res.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject(result);
}
}
}
public static async Task HttpClientGet(string url) where T : new()
{
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage res = httpClient.GetAsync(url).Result;
res.EnsureSuccessStatusCode();
var t = res.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject(t);
};
}
}
}