从HttpRequestMessage获取内容结果?

时间:2016-05-25 09:29:52

标签: c# httpclient

我有以下代码:

var client = new HttpClient()
{
    BaseAddress = new Uri(@"https://myhost:myport/"),
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

var uri = @"myurl";

var s = JsonConvert.SerializeObject(myobject);
string responseResult = string.Empty;

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, uri);
request.Content = new StringContent(s, Encoding.UTF8, "application/json");

client.SendAsync(request)
      .ContinueWith(responseTask =>
      {
           responseResult = responseTask.Result.Content.ReadAsStringAsync().Result;
      });

txtLog.Text = responseResult;

上述请求应返回字符串结果,但结果为空。我会失踪吗?

1 个答案:

答案 0 :(得分:1)

在继续运行之前,您无法使用结果,因此将作业移至Text属性进入延续:

    client.SendAsync(request)
        .ContinueWith(responseTask =>
        {
            responseResult = responseTask.Result.Content.ReadAsStringAsync().Result;
            txtLog.Text = responseResult;
        });

另一个复杂因素是只想在UI线程上设置Text属性:

    client.SendAsync(request)
        .ContinueWith(responseTask =>
        {
            responseResult = responseTask.Result.Content.ReadAsStringAsync().Result;
            Dispatcher.Invoke(() => txtLog.Text = responseResult);
        });

修改

Await / async通常更容易使用;你可以用以下代码替换上面的内容:

var message = await client.SendAsync(request);
responseResult = await message.Content.ReadAsStringAsync();
txtLog.Text = responseResult;