95 lines
3.3 KiB
C#
95 lines
3.3 KiB
C#
using System.Net;
|
|
using System.Text;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace YLErp.Modules.ApiTestModule
|
|
{
|
|
/// <summary>
|
|
/// API请求帮助类
|
|
/// </summary>
|
|
static class ApiHelper
|
|
{
|
|
//由TapQuoteConsole服务提供api服务
|
|
//端口来自TapQuoteConsole.exe.config文件中WebServerPort配置
|
|
//如果WebServerPort未配置,则不开启WEB服务
|
|
const string BaseAddress = "http://localhost:9898";
|
|
|
|
static readonly HttpClient httpClient;
|
|
|
|
static ApiHelper()
|
|
{
|
|
var handler = new HttpClientHandler {
|
|
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
|
|
};
|
|
|
|
httpClient = new HttpClient(handler) {
|
|
Timeout = new TimeSpan(0, 3, 0),
|
|
BaseAddress = new Uri(BaseAddress)
|
|
};
|
|
}
|
|
|
|
//获取访问令牌
|
|
private static string GetAccessToken()
|
|
{
|
|
using (var request = new HttpRequestMessage() {
|
|
Method = HttpMethod.Post,
|
|
RequestUri = new Uri(httpClient.BaseAddress, "api/token"),
|
|
})
|
|
{
|
|
var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes("superA:123321"));
|
|
request.Headers.Add("Authorization", "Basic " + auth);
|
|
using (var response = httpClient.SendAsync(request).Result)
|
|
{
|
|
var res = response.Content.ReadAsStringAsync().Result;
|
|
var model = JsonConvert.DeserializeObject<TokenRsp>(res);
|
|
if (model.errcode > 0)
|
|
{
|
|
throw new Exception(model.errmsg ?? "发生错误");
|
|
}
|
|
return model.accessToken;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 请求API
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="apiPath">api路径</param>
|
|
/// <param name="postData">请求数据</param>
|
|
/// <returns></returns>
|
|
public static async Task<T> RequestAsync<T>(string apiPath, object postData = null)
|
|
{
|
|
var json = await RequestAsync(apiPath, postData);
|
|
return JsonConvert.DeserializeObject<T>(json);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 请求API
|
|
/// </summary>
|
|
/// <param name="apiPath">api路径</param>
|
|
/// <param name="postData">请求数据</param>
|
|
/// <returns></returns>
|
|
public static async Task<string> RequestAsync(string apiPath, object postData = null)
|
|
{
|
|
string accessToken = GetAccessToken();
|
|
|
|
using (var request = new HttpRequestMessage() {
|
|
Method = HttpMethod.Post,
|
|
RequestUri = new Uri(httpClient.BaseAddress, apiPath.TrimStart('/')),
|
|
})
|
|
{
|
|
request.Headers.Add("Authorization", "Bearer " + accessToken);
|
|
if (postData != null)
|
|
{
|
|
var str = JsonConvert.SerializeObject(postData);
|
|
request.Content = new StringContent(str,Encoding.UTF8, "application/json");
|
|
}
|
|
|
|
var response = await httpClient.SendAsync(request);
|
|
return await response.Content.ReadAsStringAsync();
|
|
}
|
|
}
|
|
}
|
|
}
|