Windows.Web.Http.HttpClient和System.Net.Http.HttpClient收到不同的响应

时间:2017-02-16 10:45:01

标签: c# httpclient

我正在开发推特第三方应用程序。在寻找发送网络请求的方法时,我发现了两个类:Windows.Web.Http.HttpClientSystem.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发送请求。我收到了错误的回复。

(但是,当我使用网络浏览器访问请求网址时,效果不如下图所示)

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 个答案:

答案 0 :(得分:0)

问题是HttpClient没有像Nuf在评论中所说的那样解压缩gzip数据。

所以我只是为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();
}