C# 从 HttpResponseMessage 获取内容/消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15936180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:32:11  来源:igfitidea点击:

Getting content/message from HttpResponseMessage

c#windows-8windows-store-apps

提问by Clem

I'm trying to get content of HttpResponseMessage. It should be: {"message":"Action '' does not exist!","success":false}, but I don't know, how to get it out of HttpResponseMessage.

我正在尝试获取 HttpResponseMessage 的内容。它应该是:{"message":"Action '' does not exist!","success":false},但我不知道,如何从 HttpResponseMessage 中获取它。

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

In this case txtBlock would have value:

在这种情况下 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
}

采纳答案by Icemanind

You need to call GetResponse().

您需要调用GetResponse()

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

回答by MCurbelo

Try this, you can create an extension method like this:

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

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

and then, simple call the extension method:

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

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

I hope this help you ;-)

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

回答by rudivonstaden

I think the easiest approach is just to change the last line to

我认为最简单的方法就是将最后一行更改为

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

This way you don't need to introduce any stream readers and you don't need any extension methods.

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

回答by Hinrich

You can use the GetStringAsyncmethod:

您可以使用以下GetStringAsync方法:

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

回答by taras-mytofir

If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsyncextension method:

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

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

or following for synchronous code:

或以下同步代码:

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

Update: there is also generic option of ReadAsAsync<>which returns specific type instance instead of object-declared one:

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

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

回答by stanimirsp

By the answer of rudivonstaden

由 rudivonstaden 的回答

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

but if you don't want to make the method async you can use

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

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

Wait() it's important, becаuse we are doing async operations and we must wait for the task to complete before going ahead.

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

回答by snr

I think the following image helps for those needing to come by Tas the return type.

我认为下图对那些需要T作为返回类型的人有帮助。

enter image description here

在此处输入图片说明

回答by benhorgen

The quick answer I suggest is:

我建议的快速答案是:

response.Result.Content.ReadAsStringAsync().Result

response.Result.Content.ReadAsStringAsync().Result