2017-02-16 64 views
0

我正在開發一個twitter第三方應用程序。在尋找發送網絡請求的方式時,我發現了兩個類:Windows.Web.Http.HttpClientSystem.Net.Http.HttpClientWindows.Web.Http.HttpClient和System.Net.Http.HttpClient收到不同的響應

這兩個類似乎沒有太大區別,但他們在相同的請求中獲得了非常不同的結果。

當我用Windows.Web.Http.HttpClient發送請求時,它運行良好。

public async Task<string> Request(Method method, string url, string postData) 
{ 
    var http = new Windows.Web.Http.HttpClient(); 
    Windows.Web.Http.HttpResponseMessage response; 

    if (method == Method.POST) 
    { 

     var httpContent = new Windows.Web.Http.HttpStringContent(postData, Windows.Storage.Streams.UnicodeEncoding.Utf8); 
     httpContent.Headers.ContentType = Windows.Web.Http.Headers.HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); 
     response = await http.PostAsync(new Uri(url), httpContent); 
    } 
    else 
    { 
     response = await http.GetAsync(new Uri(url)); 
    } 

    return await response.Content.ReadAsStringAsync(); 
} 

但如果我發送帶有System.Net.Http.HttpClient請求。我收到錯誤的迴應。

(但是,當我使用Web瀏覽器訪問請求的URL,它運作良好,不喜歡下圖)

public async Task<string> Request(Method method, string url, string postData) 
{ 
    var http = new System.Net.Http.HttpClient(); 
    System.Net.Http.HttpResponseMessage response; 

    if (method == Method.POST) 
    { 

     var httpContent = new System.Net.Http.StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); 
     response = await http.PostAsync(new Uri(url), httpContent); 
    }else 
    { 
     response = await http.GetAsync(new Uri(url)); 
    } 


    return await response.Content.ReadAsStringAsync(); 
} 

這是爲什麼不同?我該如何解決這個問題?

+1

對System.Net.Http.HttpClient的屏幕截圖的響應看起來像它可能被壓縮(gzip),但HttpClient沒有解壓縮它。您可以檢查兩者的標題,請求和響應,HTTP頭是否正確發送/接收,如Accept-Encoding或Content-Encoding。您還可以檢查System.Net.Http.HttpClient是否正確地實現了HTTP2,因爲它支持[最近已經添加到.NET Framework 4.6.2](http://stackoverflow.com/a/38462037/1286670) –

+0

@如果你是對的! 'HttpClient'沒有解壓縮響應數據。所以我多寫了一些代碼。 – Mystika

回答

0

問題是HttpClient沒有解壓縮gzip數據,因爲Nuf在評論中表示。

所以我只寫了gzip解壓縮的小代碼。

public async Task<string> Request(Method method, string url, string postData) 
{ 
    var handler = new System.Net.Http.HttpClientHandler() 
    { 
     AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate 
    }; 
    var http = new System.Net.Http.HttpClient(handler); 
    System.Net.Http.HttpResponseMessage response; 
    if (method == Method.POST) 
    { 

     var httpContent = new System.Net.Http.StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); 
     response = await http.PostAsync(new Uri(url), httpContent); 
    } 
    else 
    { 
     response = await http.GetAsync(new Uri(url)); 
    } 


    return await response.Content.ReadAsStringAsync(); 
}