我试图获得HttpResponseMessage的内容。它应该是:{"message":"Action "不存在!","success":false},但我不知道,如何从HttpResponseMessage中获取它。

HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://****?action=");
txtBlock.Text = Convert.ToString(response); //wrong!

在这种情况下,txtBlock的值是:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Vary: Accept-Encoding
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Date: Wed, 10 Apr 2013 20:46:37 GMT
  Server: Apache/2.2.16
  Server: (Debian)
  X-Powered-By: PHP/5.3.3-7+squeeze14
  Content-Length: 55
  Content-Type: text/html
}

你需要调用GetResponse()。

Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();

试试这个,你可以创建一个像这样的扩展方法:

    public static string ContentToString(this HttpContent httpContent)
    {
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;
    }

然后,简单地调用扩展方法:

txtBlock.Text = response.Content.ContentToString();

我希望这对你有帮助;-)


我认为最简单的方法就是把最后一行改成

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

这样就不需要引入任何流阅读器,也不需要任何扩展方法。


你可以使用GetStringAsync方法:

var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);

如果你想将它转换为特定的类型(例如在测试中),你可以使用ReadAsAsync扩展方法:

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));

对于同步代码:

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;

更新:ReadAsAsync<>还有一个通用选项,它返回特定类型的实例,而不是对象声明的实例:

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();

鲁迪翁斯塔登的回答

txtBlock.Text = await response.Content.ReadAsStringAsync();

但如果你不想让方法异步,你可以使用

txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();

Wait()很重要,因为我们正在进行异步操作,必须等待任务完成后才能继续。


我认为下面的图像可以帮助那些需要使用T作为返回类型的人。


我建议的简单答案是:

.Result response.Result.Content.ReadAsStringAsync ()


使用块:

using System;
using System.Net;
using System.Net.Http;

This Function will create new HttpClient object, set http-method to GET, set request URL to the function "Url" string argument and apply these parameters to HttpRequestMessage object (which defines settings of SendAsync method). Last line: function sends async GET http request to the specified url, waits for response-message's .Result property(just full response object: headers + body/content), gets .Content property of that full response(body of request, without http headers), applies ReadAsStringAsync() method to that content(which is also object of some special type) and, finally, wait for this async task to complete using .Result property once again in order to get final result string and then return this string as our function return.

static string GetHttpContentAsString(string Url)
    {   
        HttpClient HttpClient = new HttpClient();
        HttpRequestMessage RequestMessage = new HttpRequestMessage(HttpMethod.Get, Url);
        return HttpClient.SendAsync(RequestMessage).Result.Content.ReadAsStringAsync().Result;
    }

更短的版本,它没有显示http请求的完整“转换”路径,并使用HttpClient对象的GetStringAsync方法。函数只是创建HttpClient类的新实例(一个HttpClient对象),使用GetStringAsync方法获取http请求的响应体(内容)作为异步任务结果\promise,然后使用该异步任务结果的. result属性获取最终字符串,然后简单地将此字符串作为函数返回。

static string GetStringSync(string Url)
    {
        HttpClient HttpClient = new HttpClient();
        return HttpClient.GetStringAsync(Url).Result;
    }

用法:

const string url1 = "https://microsoft.com";
const string url2 = "https://stackoverflow.com";

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; /*sets TLC protocol version explicitly to modern version, otherwise C# could not make http requests to some httpS sites, such as https://microsoft.com*/

Console.WriteLine(GetHttpContentAsString(url1)); /*gets microsoft main page html*/
Console.ReadLine(); /*makes some pause before second request. press enter to make second request*/
Console.WriteLine(GetStringSync(url2)); /*gets stackoverflow main page html*/
Console.ReadLine(); /*press enter to finish*/

完整的代码:


截至2022-02年的更新答案:

var stream = httpResponseMessage.Content.ReadAsStream();
var ms = new MemoryStream();
stream.CopyTo(ms);
var responseBodyBytes = ms.ToArray();