154 lines
5.0 KiB
C#
154 lines
5.0 KiB
C#
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
|
|
namespace YLErp.Modules.ApiModule
|
|
{
|
|
/// <summary>
|
|
/// HTTP请求帮助
|
|
/// </summary>
|
|
public class HttpClientWrap
|
|
{
|
|
readonly HttpClient _httpClient;
|
|
|
|
public HttpClientWrap(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
|
|
|
SetServicePointManager();
|
|
}
|
|
|
|
public HttpClientWrap(string baseAddress, int timeoutSeconds = 15)
|
|
{
|
|
if (timeoutSeconds < 1)
|
|
{
|
|
timeoutSeconds = 15;
|
|
}
|
|
|
|
var handler = new HttpClientHandler
|
|
{
|
|
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
|
|
};
|
|
|
|
_httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeoutSeconds) };
|
|
|
|
if (!string.IsNullOrWhiteSpace(baseAddress))
|
|
{
|
|
_httpClient.BaseAddress = new Uri(baseAddress);
|
|
}
|
|
|
|
SetServicePointManager();
|
|
}
|
|
|
|
private static void SetServicePointManager()
|
|
{
|
|
ServicePointManager.Expect100Continue = false;
|
|
ServicePointManager.DefaultConnectionLimit = 100;
|
|
}
|
|
|
|
public Uri BaseAddress
|
|
{
|
|
get { return _httpClient.BaseAddress; }
|
|
}
|
|
|
|
public TimeSpan TimeOut
|
|
{
|
|
get { return _httpClient.Timeout; }
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public string Get(string apiPathAndQuery, Action<HttpRequestMessage> requestHandle)
|
|
{
|
|
using (var request = new HttpRequestMessage()
|
|
{
|
|
Method = HttpMethod.Get,
|
|
RequestUri = new Uri(_httpClient.BaseAddress, apiPathAndQuery)
|
|
})
|
|
{
|
|
request.Headers.Add("Accept-Encoding", "gzip");
|
|
requestHandle?.Invoke(request);
|
|
using (var response = _httpClient.SendAsync(request).Result)
|
|
{
|
|
response.EnsureSuccessStatusCode();
|
|
return response.Content.ReadAsStringAsync().Result;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// POST提交JSON请求到WebAPI并将返回字符串结果
|
|
/// </summary>
|
|
public string PostJson(string apiPath, object postData, Action<HttpRequestMessage> requestHandle)
|
|
{
|
|
var str = JsonHelper.Serialize(postData) ?? string.Empty;
|
|
using (var content = new StringContent(str, Encoding.UTF8, "application/json"))
|
|
using (var request = new HttpRequestMessage()
|
|
{
|
|
Method = HttpMethod.Post,
|
|
RequestUri = new Uri(_httpClient.BaseAddress, apiPath),
|
|
Content = content
|
|
})
|
|
{
|
|
request.Headers.Add("Accept-Encoding", "gzip");
|
|
requestHandle?.Invoke(request);
|
|
// content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
|
LogFactory.GetLogger<HttpClientWrap>().Info($"url:{apiPath}\r\npostData:{str}\r\n{content.ToJson()}");
|
|
try
|
|
{
|
|
using (var response = _httpClient.SendAsync(request).Result)
|
|
{
|
|
response.EnsureSuccessStatusCode();
|
|
return response.Content.ReadAsStringAsync().Result;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger<HttpClientWrap>().Error(ex);
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task<string> PostMultipartFormDataAsync(string apiPath, Dictionary<string, HttpContent> postDatas, Action<HttpRequestMessage> requestHandle)
|
|
{
|
|
var postContent = new MultipartFormDataContent();
|
|
|
|
if (postDatas != null)
|
|
{
|
|
foreach (var item in postDatas)
|
|
{
|
|
postContent.Add(item.Value, item.Key);
|
|
|
|
LogFactory.GetLogger<HttpClientWrap>().Info($"url:{apiPath}\r\npostData:{item.Key}:{item.ToJson()}");
|
|
}
|
|
}
|
|
|
|
using var request = new HttpRequestMessage()
|
|
{
|
|
Method = HttpMethod.Post,
|
|
RequestUri = new Uri(_httpClient.BaseAddress, apiPath),
|
|
Content = postContent
|
|
};
|
|
request.Headers.Add("Accept-Encoding", "gzip");
|
|
requestHandle?.Invoke(request);
|
|
try
|
|
{
|
|
using var response = await _httpClient.SendAsync(request);
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadAsStringAsync();
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger<HttpClientWrap>().Error(ex);
|
|
throw;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|