using AmrControl.Common.HttpClients;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections;
namespace AmrControl.Common.HttpClients
{
public abstract class BaseHttpClient : IHttpRequest
{
///
/// httpclient
///
protected readonly HttpClient _httpClient;
///
/// 根路径
///
protected readonly string baseUri;
public BaseHttpClient(HttpClient httpClient, string baseUri)
{
_httpClient = httpClient;
this.baseUri = baseUri;
}
public HttpRespResult sendRequest(string url, T data)
{
return sendRequest(url, new(), data);
}
public HttpRespResult sendRequest(string url, Dictionary headers, T data)
{
var response = _httpClient.SendAsync(createRequest(reHandleUrl(url, data), headers, getMethod(), handleData(data))).Result;
var rs = response.Content.ReadAsStringAsync().Result;
return handleResult(response, rs);
}
///
/// 处理数据
///
///
///
protected abstract HttpContent? handleData(T data);
///
/// 当前请求类型
///
///
protected abstract HttpMethod getMethod();
///
/// 处理url,针对get等部分请求可能需要将参数放在url后面,此处做处理
///
///
///
///
protected virtual string reHandleUrl(string url, T data)
{
if (baseUri.EndsWith("/"))
{
if (url.StartsWith("/"))
{
url = url[1..];
}
return baseUri + url;
}
else
{
if (url.StartsWith("/"))
{
return baseUri + url;
}
else
{
return baseUri + "/" + url;
}
}
}
///
/// 创建请求对象
///
///
///
///
///
///
protected HttpRequestMessage createRequest(string url, Dictionary headers, HttpMethod method, HttpContent? content)
{
var request = new HttpRequestMessage
{
Method = method,
RequestUri = new Uri(url),
Content = content
};
foreach (var head in headers)
{
request.Headers.Add(head.Key, head.Value);
}
return request;
}
///
/// 解析结果
///
///
///
///
protected HttpRespResult handleResult(HttpResponseMessage response, string rs)
{
return new HttpRespResult()
{
code = response.IsSuccessStatusCode ? 200 : -1,
message = response.IsSuccessStatusCode ? "发送成功" : rs,
data = rs
};
}
///
/// 类型转换
///
///
///
///
protected Dictionary convertObj2Dict(T data)
{
Dictionary dict = new Dictionary();
if (data != null)
{
if (data is Dictionary)
{
//若对象本身即是dictionary则直接返回
return data as Dictionary;
}
else if (data is IEnumerable || data.GetType().IsArray)
{
throw new Exception("不支持的转换类型");
}
else
{
return JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(data, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
}
}
return dict;
}
}
}