using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace DaJiaoYan.Utils
{
public static class Http
{
public struct Response
{
public HttpStatusCode code;
public HttpContent message;
public string url;
}
public struct Request
{
///
/// 请求的网址
///
public string uri;
///
/// 头信息
///
public Dictionary headers;
///
/// 请求的数据
///
public Dictionary data;
///
/// 上传的文件
///
public Dictionary files;
///
/// 上传的文件二进制流
///
public Dictionary fileStream;
///
/// 请求类型
///
public RequestContentType contentType;
///
/// 请求方式
///
public Method method;
public void Init()
{
uri = "";
headers = new Dictionary();
data = new Dictionary();
files = new Dictionary();
fileStream = new Dictionary();
contentType = RequestContentType.Default;
method = Method.Get;
}
public Request(string uri, Method method)
{
this.uri = uri;
this.method = method;
this.headers = new Dictionary();
this.data = null;
files = null;
fileStream = null;
contentType = RequestContentType.Default;
}
public Request(string uri, Method method, Dictionary data)
{
this.uri = uri;
this.method = method;
this.headers = new Dictionary();
this.data = data;
files = null;
fileStream = null;
contentType = RequestContentType.Default;
}
public Request(string uri, Method method, Dictionary headers, Dictionary data)
{
this.uri = uri;
this.method = method;
this.headers = headers;
this.data = data;
files = null;
fileStream = null;
contentType = RequestContentType.Default;
}
public Request(string uri, Method method, RequestContentType contentType, Dictionary headers, Dictionary data)
{
this.uri = uri;
this.method = method;
this.headers = headers;
this.data = data;
files = null;
fileStream = null;
this.contentType = contentType;
}
public Request(string uri, Method method, Dictionary headers, Dictionary data, Dictionary files)
{
this.uri = uri;
this.method = method;
this.headers = headers;
this.data = data;
this.files = files;
fileStream = null;
contentType = RequestContentType.Default;
}
public Request(string uri, Method method, Dictionary headers, Dictionary data, Dictionary files, Dictionary fileStream)
{
this.uri = uri;
this.method = method;
this.headers = headers;
this.data = data;
this.files = files;
this.fileStream = fileStream;
contentType = RequestContentType.Default;
}
}
///
/// 请求内容类型
///
public enum RequestContentType
{
Default, Json
}
///
/// 请求方法
///
public enum Method
{
Get, Post, Put, Delete, Patch
}
///
/// 初始化请求头
///
///
///
private static void InitClientHeaders(ref HttpClient httpClient, Dictionary headers)
{
if (headers != null)
{
foreach (var header in headers)
{
if (!string.IsNullOrEmpty(header.Key) && !string.IsNullOrEmpty(header.Value.ToString()))
{
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value.ToString());
}
}
}
}
///
/// 获取
///
///
///
public static async Task Fetch(Request request)
{
HttpResponseMessage response;
try
{
switch (request.method)
{
case Method.Post:
response = await Post(request);
break;
case Method.Put:
response = await Put(request);
break;
case Method.Patch:
response = await Patch(request);
break;
case Method.Delete:
response = await Delete(request);
break;
default:
response = await Get(request);
break;
}
}
catch (Exception ex)
{
Log.Error(ex);
response = new HttpResponseMessage();
}
return response;
}
public static async Task Get(Request request)
{
HttpResponseMessage response = null;
if (!string.IsNullOrEmpty(request.uri))
{
HttpClient client = new HttpClient();
string url = request.uri;
InitClientHeaders(ref client, request.headers);
if (request.data != null)
{
url = string.Concat(url, "?");
foreach (var item in request.data)
{
url = string.Concat(url, $"{item.Key}={HttpUtility.UrlEncode(item.Value.ToString())}&");
}
url = url.Substring(0, url.Length - 1);
}
try
{
response = await client.GetAsync(url);
}
catch (Exception ex)
{
Log.Error(ex);
}
finally
{
client?.Dispose();
}
}
return response;
}
private static HttpContent InitNonGetContent(Request request)
{
HttpContent content;
if (request.contentType == RequestContentType.Json)
{
// 发送json 数据
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(request.data), Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content = httpContent;
}
else
{
// 普通的键值对提交
MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent();
if (request.files != null)
{
foreach (var file in request.files)
{
multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(file.Value)), file.Key, Path.GetFileName(file.Value));
}
}
if (request.fileStream != null)
{
foreach (var file in request.fileStream)
{
multipartFormDataContent.Add(new ByteArrayContent(file.Value), file.Key, file.Key);
}
}
if (request.data != null)
{
foreach (var d in request.data)
{
multipartFormDataContent.Add(new StringContent(d.Value.ToString(), Encoding.UTF8), d.Key);
}
}
content = multipartFormDataContent;
}
return content;
}
public static async Task Post(Request request)
{
HttpResponseMessage response = null;
if (!string.IsNullOrEmpty(request.uri))
{
HttpClient client = new HttpClient();
HttpContent content = InitNonGetContent(request);
try
{
InitClientHeaders(ref client, request.headers);
response = await client.PostAsync(request.uri, content);
}
catch (Exception ex)
{
Log.Error(ex);
}
finally
{
client?.Dispose();
}
}
return response;
}
public static async Task Patch(Request request)
{
HttpResponseMessage response = null;
if (!string.IsNullOrEmpty(request.uri))
{
HttpClient client = new HttpClient();
HttpContent content = InitNonGetContent(request);
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), request.uri);
try
{
InitClientHeaders(ref client, request.headers);
httpRequestMessage.Content = content;
response = await client.SendAsync(httpRequestMessage);
}
catch (Exception ex)
{
Log.Error(ex);
}
finally
{
client?.Dispose();
}
httpRequestMessage.Dispose();
}
return response;
}
public static async Task Put(Request request)
{
HttpResponseMessage response = null;
if (!string.IsNullOrEmpty(request.uri))
{
HttpClient client = new HttpClient();
HttpContent content = InitNonGetContent(request);
try
{
InitClientHeaders(ref client, request.headers);
response = await client.PutAsync(request.uri, content);
//client.Dispose();
}
catch (Exception ex)
{
Log.Error(ex);
}
finally
{
client?.Dispose();
}
}
return response;
}
public static async Task Delete(Request request)
{
HttpResponseMessage response = null;
if (!string.IsNullOrEmpty(request.uri))
{
HttpClient client = new HttpClient();
string url = request.uri;
try
{
InitClientHeaders(ref client, request.headers);
if (request.data != null)
{
url = string.Concat(url, "?");
foreach (var item in request.data)
{
url = string.Concat(url, $"{item.Key}={HttpUtility.UrlEncode(item.Value.ToString())}&");
}
}
response = await client.DeleteAsync(request.uri);
}
catch (Exception ex)
{
Log.Error(ex);
}
finally
{
client?.Dispose();
}
}
return response;
}
}
}