在PCL异步调用与HttpClient的 [英] Async call with HttpClient in PCL
问题描述
我了PCL中,我想打一个异步调用usingg HttpClient的。 I codeD这样的
I have a PCl in which I want to make a async call usingg HttpClient. I coded like this
public static async Task<string> GetRequest(string url)
{
var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
HttpResponseMessage response = await httpClient.GetAsync(url);
return response.Content.ReadAsStringAsync().Result;
}
不过,伺机正显示出错误无法等待System.net.http.htt presponsemessage之类的消息。
But await is showing error "cannot await System.net.http.httpresponsemessage" like message.
如果我用code这样比一切顺利,但不是在异步方式
If I use code like this than everything goes well but not in async way
public static string GetRequest(string url)
{
var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
HttpResponseMessage response = httpClient.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
我只是想,这种方法在异步的方式执行。任何帮助,请。
I just want that this method executes in async way. Any help please.
这是屏幕截图。
This is the screen shot.
推荐答案
按照 TAP准则,不要忘了叫 EnsureSuccessStatus code
,配置你的资源,并更换所有的结果
s的的await
取值:
Follow the TAP guidelines, don't forget to call EnsureSuccessStatusCode
, dispose your resources, and replace all Result
s with await
s:
public static async Task<string> GetRequestAsync(string url)
{
using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
如果您code不需要做别的,的HttpClient
有一个 GetStringAsync
方法这是否为您:
If your code doesn't need to do anything else, HttpClient
has a GetStringAsync
method that does this for you:
public static async Task<string> GetRequestAsync(string url)
{
using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
return await httpClient.GetStringAsync(url);
}
如果您共享的HttpClient
情况下,这可以简化为:
If you share your HttpClient
instances, this can simplify to:
private static readonly HttpClient httpClient =
new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
public static Task<string> GetRequestAsync(string url)
{
return httpClient.GetStringAsync(url);
}
这篇关于在PCL异步调用与HttpClient的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!