如何在MessageBox中显示httpwebresponse(JSON)的值?

时间:2018-04-10 14:57:12

标签: c# httpwebrequest response fiddler

如何在MessageBox中显示httpwebresponse的值? 我创建了webreq,其中我得到的响应是json。

{ "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": { "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?", "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }

我希望在MessageBox中显示此响应 这是我的c#代码

        //Removed Main code
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        WebHeaderCollection header = response.Headers;
        var encoding = ASCIIEncoding.ASCII;
        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
        {
            string responseText = reader.ReadToEnd();
            System.Windows.Forms.MessageBox.Show(responseText);
        }

当我试图表明它显示像这样一些符号 Before Opening Fiddler

当我打开fiddler并运行C#代码时,它会正确显示为什么? After Opening Fiddler 怎么解决?

1 个答案:

答案 0 :(得分:0)

网站似乎正在使用压缩来满足您的请求,Fiddler正在删除。

您可以要求HttpWebRequest自动为您解压缩响应:

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

所以你的完整代码是:

//Removed Main code
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
    string responseText = reader.ReadToEnd();
    System.Windows.Forms.MessageBox.Show(responseText);
}