62,046
社区成员
发帖
与我相关
我的任务
分享
private async Task checkParameterAndTokenAsync(string path, bool needAuthorization = true)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (needAuthorization && (Config.ManagerToken == null || Config.ManagerToken.IsExpired()))
{
await TokenAsync();
}
}
private HttpClient prepareRequestClient(bool isPost, bool needAuthorization = true)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri($"{Config.base_address}/{Config.org_name}/{Config.app_name}/" );
if (isPost)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
if (needAuthorization)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", $"Bearer {Config.ManagerToken.access_token}");
}
return client;
}
/// <summary>
/// 获取Token并保存
/// </summary>
/// <returns></returns>
public async Task<ManagerToken> TokenAsync()
{
var dict = new Dictionary<string, string>();
dict.Add("grant_type", "client_credentials");
dict.Add("client_id", Config.client_id);
dict.Add("client_secret", Config.client_secret);
string bodyJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
var resultString = await PostAsync("token", false, bodyJson);
if (!string.IsNullOrEmpty(resultString))
{
var token = Newtonsoft.Json.JsonConvert.DeserializeObject<ManagerToken>(resultString);
token.timestamp = DateTime.Now.ToTimestamp();
//保存Token的IO操作,不关心本次保存是否成功,异步调用,不等待
Task task = Config.SaveTokenAsync(token);
return token;
}
return null;
}
public async Task<string> PostAsync(string path, bool needAuthorization = true, string bodyJson = null)
{
await checkParameterAndTokenAsync(path, needAuthorization);
using (HttpClient client = prepareRequestClient(true, needAuthorization))
{
try
{
var content = (!string.IsNullOrEmpty(bodyJson)) ? new StringContent(bodyJson, Encoding.Default, "application/json") : null;
var response = await client.PostAsync(path, content);
//var response = client.PostAsync(path, content).Result;
if(response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return string.Empty;
}
catch(Exception ex)
{
return string.Empty;
}
}
}
var token = request.TokenAsync().Result;