POST接口底层方法
对于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 });//以登录为例
人说,如果你很想要一样东西,就放它走 。如果它回来找你,那么它永远都是你的。要是它没有回来,那么不用再等了,因为它根本就不是你的。
——伊恩·麦克尤恩