从任务获取HttpResponseMessage<;HttpResponseMessage>;

本文关键字:HttpResponseMessage gt 任务 lt 获取 | 更新日期: 2023-09-27 17:59:00

在HttpClient内部使用语句,我需要从某处打开HttpResponseMessage。

using (HttpClient client = new HttpClient())
{
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authUser);
     Task<HttpResponseMessage> m = client.GetAsync(url);   
     // HttpResponseMessage msg = ???              
     task.Wait();
     return task.Result;
}

我的问题是:如何从这一行获取HttpResponseMessage

Task<HttpResponseMessage> m = client.GetAsync(url);   

从任务获取HttpResponseMessage<;HttpResponseMessage>;

您应该await任务:

HttpResponseMessage m = await client.GetAsync(url);   

为此,需要将调用方法标记为async

要获得HttpResponseMessasge,您应该使用Task.Result属性。以下是您的代码(有点修改),其中HttpResponseMessage来自任务:

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authUser);
    Task<HttpResponseMessage> task = client.GetAsync(uri);
    **HttpResponseMessage msg = task.Result;**
    task.Wait();
    return task.Result;
}
相关文章:
  • 没有找到相关文章