"Unexpected character exception" 使用 Flurl 向 StackExchange API 发出 GET 请求时

"Unexpected character exception" when making GET request to StackExchange API using Flurl

我创建了一个控制台应用程序,我在其中向 Stack Exchange API 发出简单的 GET 请求以获取一些评论。我正在使用 Flurl。此方法是从 Main

调用的
private static async Task GetComments()
{
    dynamic d = await "https://api.stackexchange.com/2.2/comments?page=1&pagesize=5&order=desc&min=1513468800&max=1513555200&sort=creation&site=Whosebug"
                        .GetJsonAsync();
}

但是,我得到这个错误:

{"Unexpected character encountered while parsing value: \u001f. Path '', line 0, position 0."}

我试过这样设置 headers,但没有成功。

dynamic d = await new Url("https://api.stackexchange.com/2.2/comments.....")
               .WithHeader("Content-Encoding", "gzip")
               .WithHeader("Accept-Encoding", "gzip")
               .GetJsonAsync();

当我 open it in the browser

时,URL 确实 return 正确 JSON

所以 Flurl 似乎不支持开箱即用的 Gzip,要让它工作需要一些改进。首先你需要一个自定义的 Http 客户端工厂:

public class GzipClientFactory : Flurl.Http.Configuration.IHttpClientFactory
{
    public HttpMessageHandler CreateMessageHandler() => new HttpClientHandler()
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
    };

    public HttpClient CreateHttpClient(HttpMessageHandler handler) => 
        new HttpClient(handler);
}

现在配置 Flurl 以使用它:

FlurlHttp.Configure(settings => {
    settings.HttpClientFactory = new GzipClientFactory();
});

现在将支持 Gzip 压缩:

dynamic d = await new Url("https://api.stackexchange.com/2.2/comments.....")
               .GetJsonAsync();

更新: Flurl.Http 现在默认支持自动解压,所以只需 upgrade 就可以避免所有这些。


这是一个类似于已接受答案的选项,除了它 适用于对 api.stackexchange.com 的调用,并且它或多或少是一个单行。启动时调用一次:

FlurlHttp.ConfigureClient("https://api.github.com", cli => 
    ((HttpClientHandler)cli.HttpMessageHandler).AutomaticDecompression =
        DecompressionMethods.GZip | DecompressionMethods.Deflate);

附带说明一下,在自动解压方面,Flurl 的默认设置与 HttpClient 的默认设置完全相同。评论中有说明 GZIP 与 HttpClient 一起工作,这让我摸不着头脑,但似乎与 HttpClient 有 differences 取决于 platform/version。为了让事情变得更容易和更可预测,我正在考虑在 Flurl 中默认支持 GZIP/DEFLATE,但我首先需要了解性能等方面的影响

Flurl.Http 2.2 只是 released, and it will now automatically decompress GZIP and DEFLATE by default。所以,新的最佳答案是:升级。 :)

现在是 2019 年,我找不到适合 dotnet 的库来使用 API。所以我自己创建了一个。还有很长的路要走。只要我 can.It 将其作为 nuget 发布,我就计划维护它,您可以在 Github

上查看源代码

来自 Nuget

Install-Package StackExchange.NET -Version 1.1.0