简体   繁体   English

HttpWebResponse文本似乎不是JSON

[英]HttpWebResponse text does not appear to be JSON

I am making a rest call in which I get a HttpWebResponse that contains data. 我正在进行一次休息呼叫,在其中我得到一个包含数据的HttpWebResponse。 It seems the data is serialized, and I am trying to get the plain text of the request. 似乎数据已序列化,我正在尝试获取请求的纯文本。 I have been using the chrome extension Advanced Rest client, which when calling the same request it is able to display the text version of the json response. 我一直在使用chrome扩展Advanced Rest客户端,该客户端在调用相同的请求时能够显示json响应的文本版本。

From what I have read on here, you are required to deserialize into the expected object. 根据我在这里阅读的内容,您需要反序列化为预期的对象。 However, it is pretty clear that chrome plugin has no idea about the object type and can still print out plain text. 但是,很明显chrome插件对对象类型一无所知,仍然可以打印出纯文本。

Is it possible to do the same in c#? 是否可以在C#中执行相同的操作?

HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

request.Method = "POST";
request.ContentType = "application/json";

// [code removed for setting json data via stream writer


using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{

   // This is where I am trying to figure out how to get plain readable text out of response.GetResponseStream()

}

Edit: If I simply use a StreamReader to get the text from the response stream, I get a bunch of binary data and not the plain json text. 编辑:如果我只是使用StreamReader从响应流中获取文本,我会得到一堆二进制数据,而不是纯json文本。

Edit: realized the problem had to do with compression. 编辑:意识到问题与压缩有关。 This can be closed. 这可以关闭。

I'm not sure if got it right, but you can get the response as a string doing this: 我不确定是否正确,但是您可以通过以下方式获得响应:

using (var sr = new StreamReader(response.GetResponseStream()))
{
    text = sr.ReadToEnd();
}

Turned out my problem was due to compression. 原来我的问题是由于压缩。 I realized the header contained "Content-Encoding: gzip" so I searched on how to unzip with gzip compression and then the text was proper json. 我意识到标题包含“ Content-Encoding:gzip”,所以我搜索了如何使用gzip压缩解压缩,然后文本是正确的json。 Thanks all 谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM