在 C# 中获取一些无效响应(一些随机字符)

Getting some invalid response(some random characters) in c#

我正在用 C# 做一个获取请求,但我收到一些比原始内容无效的响应

代码

using System;
using System.Net;
using System.Text;
using System.IO;


public class Test
{
    // Specify the URL to receive the request.
    public static void Main(string[] args)
    {
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www1.bloomingdales.com/api/store/v2/stores/367,363,6113,364,4946?upcNumber=849262004629");

        // Set some reasonable limits on resources used by this request
        myHttpWebRequest.MaximumAutomaticRedirections = 4;
        myHttpWebRequest.MaximumResponseHeadersLength = 4;
        // Set credentials to use for this request.
        myHttpWebRequest.Credentials = CredentialCache.DefaultCredentials;
        myHttpWebRequest.Method = "GET";
        myHttpWebRequest.AllowAutoRedirect = false;
        myHttpWebRequest.ContentLength = 0;
        myHttpWebRequest.Accept = "application/json, text/javascript, */*; q=0.01";
        myHttpWebRequest.Headers.Add("Cookie", "ShippingCountry=US;");
        myHttpWebRequest.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36";
        myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
        myHttpWebRequest.Headers.Add("Accept-Language", "en-US,en;q=0.8");
        myHttpWebRequest.Headers.Add("X-Macys-ClientId", "NavApp");
        var response = (HttpWebResponse)myHttpWebRequest.GetResponse();
        var rmyResponseHeaders = response.Headers;

        Console.WriteLine("Content length is {0}", response.ContentLength);
        Console.WriteLine("Content type is {0}", response.ContentType);

        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream();

        // Pipes the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

        Console.WriteLine("Response stream received.");
        Console.WriteLine(readStream.ReadToEnd());
        Console.ReadLine();
        response.Close();
        readStream.Close();
    }
}

上面的字符无效,例如 ????????和其他一些角色

您可以在此处查看原始回复

curl 'http://www1.bloomingdales.com/api/store/v2/stores/367,363,6113,364,4946?upcNumber=849262004629' -H 'Cookie:shippingCountry=US;' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36' -H 'Accept-Language: en-US,en;q=0.8' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'X-Macys-ClientId: NavApp' --compressed

如何解决这个问题并获得准确的回复(原始回复)?

您没有解压缩响应流。将 Accept-Encoding header 设置为空字符串,直到您准备好找出使用了哪种压缩方式并将其解压缩。