using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using System;
using System.Web;
namespace PdmSwPlugin.Common.Util.Http
{
public static class HttpUtil
{
///
/// Http GET 同步获取对象
///
/// 对象类型
/// 客户端
/// url
/// 参数
/// Http返回结果
public static Result GetSyncAction(this HttpClient client, string url, params object[] models)
{
return JsonUtil.Deserialize>(GetSyncAction(client, url, models));
}
///
/// Http GET 同步获取字符
///
/// 客户端
/// url
/// 参数
/// Http返回结果
public static string GetSyncAction(this HttpClient client, string url, params object[] models)
{
try
{
foreach (object model in models)
{
url = url.ModelToUriParam(model);
}
Task task = client.GetStringAsync(url);
task.Wait();
return task.Result;
}
catch (Exception e)
{
throw new PdmException("请求异常", e);
}
}
///
/// Http GET 异步获取对象
///
/// 对象类型
/// 客户端
/// url
/// 参数
/// 异步Http返回结果
public static async Task> GetAsyncAction(this HttpClient client, string url, params object[] models)
{
try
{
foreach (object model in models)
{
url = url.ModelToUriParam(model);
}
return JsonUtil.Deserialize>(await client.GetStringAsync(url));
}
catch (Exception e)
{
throw new PdmException("请求异常", e);
}
}
///
/// Http POST 同步获取对象
///
/// 对象类型
/// 客户端
/// url
/// 参数json字符
/// Http返回结果
public static Result PostSyncAction(this HttpClient client, string url, string data)
{
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
Task task = client.PostAsync(url, content);
task.Wait();
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
Task task2 = response.Content.ReadAsStringAsync();
task2.Wait();
string responseBody = task2.Result;
return JsonUtil.Deserialize>(responseBody);
}
///
/// Http POST 同步获取对象
///
/// 对象类型
/// 客户端
/// url
/// Http负载
/// Http返回结果
public static Result PostSyncAction(this HttpClient client, string url, HttpContent content)
{
Task task = client.PostAsync(url, content);
task.Wait();
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
Task task2 = response.Content.ReadAsStringAsync();
task2.Wait();
return JsonUtil.Deserialize>(task2.Result);
}
///
/// Http POST 同步获取对象
///
/// 对象类型
/// 客户端
/// 参数对象
/// url
/// Http返回结果
public static Result PostSyncAction(this HttpClient client, object data, string url)
{
string dataStr = JsonUtil.Serialize(data);
StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
Task task = client.PostAsync(url, content);
task.Wait();
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
Task task2 = response.Content.ReadAsStringAsync();
task2.Wait();
string responseBody = task2.Result;
return JsonUtil.Deserialize>(responseBody);
}
public static string PostSyncAction(this HttpClient client, string url, string data)
{
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
Task task = client.PostAsync(url, content);
task.Wait();
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
Task task2 = response.Content.ReadAsStringAsync();
task2.Wait();
return task2.Result;
}
public static async Task PostAsyncAction(this HttpClient client, string url, string data)
{
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
_ = response.EnsureSuccessStatusCode();
return JsonUtil.Deserialize(await response.Content.ReadAsStringAsync());
}
public static async Task> PostAsyncAction(this HttpClient client, string url, object data)
{
string dataStr = JsonUtil.Serialize(data);
StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
_ = response.EnsureSuccessStatusCode();
return JsonUtil.Deserialize>(await response.Content.ReadAsStringAsync());
}
public static async Task> PostAsyncAction(this HttpClient client, string url, HttpContent content)
{
HttpResponseMessage response = await client.PostAsync(url, content);
_ = response.EnsureSuccessStatusCode();
return JsonUtil.Deserialize>(await response.Content.ReadAsStringAsync());
}
///
/// 下载文件保存到绝对路径
///
///
///
///
///
public static async Task GetDownload(this HttpClient client, string url, string absolutePath, params object[] models)
{
foreach (object model in models)
{
url = url.ModelToUriParam(model);
}
HttpResponseMessage response = await client.GetAsync(url);
int code = Convert.ToInt32(response.StatusCode);
if (code == 200)
{
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
using (FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate))
{
byte[] buffer = new byte[1024];
int readLength = 0;
int length;
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
readLength += length;
fs.Write(buffer, 0, length);
}
}
}
}
else
{
string error = "图纸下载失败";
if (response.Headers.TryGetValues("FileName", out IEnumerable values)){
error = values.First();
}
throw new PdmException(error);
}
}
///
/// 下载文件保存到绝对路径
///
///
///
///
///
public static void GetDownloadSync(this HttpClient client, string url, string absolutePath, params object[] models)
{
foreach (object model in models)
{
url = url.ModelToUriParam(model);
}
Task task = client.GetAsync(url);
task.Wait();
HttpResponseMessage response = task.Result;
int code = Convert.ToInt32(response.StatusCode);
if (code == 200)
{
Task task2 = response.Content.ReadAsStreamAsync();
task2.Wait();
using (Stream stream = task2.Result)
{
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
using (FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate))
{
byte[] buffer = new byte[1024];
int readLength = 0;
int length;
while ((length = stream.Read(buffer, 0, buffer.Length)) != 0)
{
readLength += length;
fs.Write(buffer, 0, length);
}
}
}
}
else
{
string error = "图纸下载失败";
if (response.Headers.TryGetValues("FileName", out IEnumerable values))
{
error = HttpUtility.UrlDecode(values.First());
}
throw new PdmException(error);
}
}
///
/// 下载文件到指定文件夹
///
///
///
///
///
///
public static async Task GetDownload(this HttpClient client, string url, string dir, string fileName, params object[] models)
{
foreach (object model in models)
{
url = url.ModelToUriParam(model);
}
HttpResponseMessage response = await client.GetAsync(url);
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
{
byte[] buffer = new byte[1024];
int readLength = 0;
int length;
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
readLength += length;
fs.Write(buffer, 0, length);
}
}
}
}
public static async void GetDownloadWithName(this HttpClient client, string url, string dir, params object[] models)
{
foreach (object model in models)
{
url = url.ModelToUriParam(model);
}
HttpResponseMessage response = await client.GetAsync(url);
string fileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault());
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
{
byte[] buffer = new byte[1024];
int readLength = 0;
int length;
while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
readLength += length;
fs.Write(buffer, 0, length);
}
}
}
}
public static string ModelToUriParam(this string url, object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
StringBuilder sb = new StringBuilder()
.Append(url).Append("?");
if (obj is Dictionary)
{
Dictionary dict = (Dictionary)obj;
foreach (var item in dict)
{
if (item.Value == null || string.IsNullOrWhiteSpace(item.Value))
{
continue;
}
sb = sb.Append(item.Key)
.Append("=")
.Append(HttpUtility.UrlEncode(item.Value))
.Append("&");
}
}
else
{
foreach (PropertyInfo p in properties)
{
object v = p.GetValue(obj, null);
if (v == null || string.IsNullOrWhiteSpace(v.ToString()))
{
continue;
}
sb = sb.Append(p.Name)
.Append("=")
.Append(HttpUtility.UrlEncode(v.ToString()))
.Append("&");
}
}
sb = sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
}
}