簡體   English   中英

在C#中使用StackOverflow檢索JSON

[英]Retrieve JSON with StackOverflow in C#

我的問題非常簡單,並且在代碼注釋中不言自明。 使用不同於StackOverflow的URL時,Json毫無問題地出現,但是,從StackOverflow獲得的Json則具有奇怪的編碼形式。

這是我的代碼:

    static void Main(string[] args)
    {
        //goodUrl is working in this program and in the browser.
        string goodUrl = "http://yuml.me/23db58a4.json";
        //badUrl is not working in this program, but works fine in the browser.
        string badUrl = "https://api.stackexchange.com/2.1/me?key=qxtbTbIIEhAZFGO0QOziMA((&site=stackoverflow&order=desc&sort=reputation&access_token=mytoken&filter=!23IiyZnRyYmQ4bPZYWRA1";
        HttpWebRequest webRequest = System.Net.WebRequest.Create(badUrl) as HttpWebRequest;
        webRequest.Method = "GET";
        webRequest.ServicePoint.Expect100Continue = false;
        StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
        try
        {
            string str = responseReader.ReadToEnd();
            //With Bad-url, "str" ENCODE JSON but with STRANGE ASCII CODE.
            Console.Write(str);
            Console.Read();
        }
        //...
    }  

真正的問題在哪里,我該如何解決?

您得到壓縮的結果。

var stream = webRequest.GetResponse().GetResponseStream();
MemoryStream m = new MemoryStream();
new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress).CopyTo(m);
try
{
    string str = Encoding.UTF8.GetString(m.ToArray()); 
    Console.Write(str);
    Console.Read();
}
finally
{
 ........
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM