对于POST请求的接口,我们如何调用它获取到数据,这其中自然少不了底层代码
底层公共类的书写
public class ThirdOpenAPIService
{
public static ThirdOpenAPIHttpAsyncClient Client = new ThirdOpenAPIHttpAsyncClient(); //HTTP异步客户端
public static async Task<T> PostHttp<T>(string requestUri, object data)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("userUID", UserUID.ToString());
client.DefaultRequestHeaders.Add("token", Token);
string str = JsonHelper.Instance.Serialize(data);
var content = new StringContent(str)
{
Headers = { ContentType = new MediaTypeHeaderValue("Application/json") }
};
HttpResponseMessage var = await client.PostAsync(requestUri, content);
if (var.IsSuccessStatusCode)
{
return await var.Content.ReadAsAsync<T>();
}
return default(T);
}
}
public static Guid UserUID { get; set; }
public static string Token { get; set; }
}
那么在服务逻辑层我们应该怎么写呢,只需要按照一般的写法即可
ThirdOpenAPIService.UserUID = 记录的Cookie用户唯一ID
var response = await ThirdOpenAPIService.PostHttp<ThirdOpenAPIResponse<T>>(ThirdOpenAPIService.RequestUri(ApiUrls.User.login), new { userName = username, password = pwdCiphertext });//以登录为例