using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace YLErp.Modules.ApiTestModule
{
///
/// API请求帮助类
///
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(res);
if (model.errcode > 0)
{
throw new Exception(model.errmsg ?? "发生错误");
}
return model.accessToken;
}
}
}
///
/// 请求API
///
///
/// api路径
/// 请求数据
///
public static async Task RequestAsync(string apiPath, object postData = null)
{
var json = await RequestAsync(apiPath, postData);
return JsonConvert.DeserializeObject(json);
}
///
/// 请求API
///
/// api路径
/// 请求数据
///
public static async Task 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();
}
}
}
}