public static class HttpClientUtil
{
///
/// 发起POST同步请求
///
///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
/// 填充消息头
///
public static string HttpPost(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary? headers = null)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
///
/// 发起POST异步请求
///
///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
/// 填充消息头
///
public static async Task HttpPostAsync(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary? headers = null)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = await client.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
}
///
/// 发起GET同步请求
///
///
///
///
///
public static string HttpGet(string url, string contentType = "application/json", Dictionary? headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
///
/// 发起GET异步请求
///
///
///
///
///
public static async Task HttpGetAsync(string url, string contentType = "application/json", Dictionary? headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
}
///
/// 发起POST同步请求
///
///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
/// 填充消息头
///
public static T? HttpPost(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary? headers = null)
{
return HttpPost(url, postData, contentType, timeOut, headers).ToEntity();
}
///
/// 发起POST异步请求
///
///
///
/// application/xml、application/json、application/text、application/x-www-form-urlencoded
/// 填充消息头
///
public static async Task HttpPostAsync(string url, string? postData = null, string contentType = "application/json", int timeOut = 30, Dictionary? headers = null)
{
var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
return res.ToEntity();
}
///
/// 发起GET同步请求
///
///
///
///
///
public static T? HttpGet(string url, string contentType = "application/json", Dictionary? headers = null)
{
return HttpGet(url, contentType, headers).ToEntity();
}
///
/// 发起GET异步请求
///
///
///
///
///
public static async Task HttpGetAsync(string url, string contentType = "application/json", Dictionary? headers = null)
{
var res = await HttpGetAsync(url, contentType, headers);
return res.ToEntity();
}
///
/// 上传文件
///
///
///
///
public static string UploadFile(string url, string fileUrl)
{
Stream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
var formData = new MultipartFormDataContent();
byte[] data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
formData.Add(new StreamContent(fileStream),"file", fileUrl);
// 实例化HttpClient
using (HttpClient client = new HttpClient())
{
// 发送请求
HttpResponseMessage result = client.PostAsync(url, formData).Result;
// 接受结果
string responseResult = result.Content.ReadAsStringAsync().Result;
// 打印结果
Console.WriteLine(responseResult);
client.Dispose();
fileStream.Close();
return responseResult;
}
}
}
///
/// Json扩展方法
///
public static class JsonExtends
{
public static T? ToEntity(this string val)
{
return JsonConvert.DeserializeObject(val);
}
//public static List ToEntityList(this string val)
//{
// return JsonConvert.DeserializeObject>(val);
//}
public static string ToJson(this T entity, Formatting formatting = Formatting.None)
{
return JsonConvert.SerializeObject(entity, formatting);
}
}
Console.WriteLine("===========================================================");
Console.WriteLine("================后台模拟Http请求调用Api====================");
Console.WriteLine("===========================================================");
try
{
//get请求
string userResult = HttpClientUtil.HttpGet("https://www.baidu.com/");
//post请求
string parameter = Newtonsoft.Json.JsonConvert.SerializeObject(new User()
{
Id = 234,
Name = "Richard",
Age = 37
});
string result = HttpClientUtil.HttpPost("https://www.baidu.com/", parameter);
//文件上传
string uploadResult = HttpClientUtil.UploadFile("https://www.baidu.com/", "这里是一个文件上传的测试文件.doc");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}