在HttpClient中解压缩Brotli HttpResponse [英] Decompress Brotli HttpResponse in a HttpClient

查看:262
本文介绍了在HttpClient中解压缩Brotli HttpResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web Api,向我发送的响应用brotli压缩,我有一个控制台应用程序,通过向我的WebApi请求数据,该应用程序使用HttpClient.我需要解压缩WebApi发送的数据.

I have a Web Api that send me the responses compress with brotli and I have a console app that use a HttpClient by request the data to my WebApi. I need decompress the data send by my WebApi.

对于.Net Core 2.2

For .Net Core 2.2

Startup.cs

Startup.cs

//对服务器的保留权

services.Configure<BrotliCompressionProviderOptions>(opciones =>
                opciones.Level = CompressionLevel.Optimal
);

services.AddResponseCompression(opciones =>
{
    opciones.EnableForHttps = true;
    opciones.Providers.Add<BrotliCompressionProvider>();
});

ConseleApp

ConseleApp

using (var client = new HttpClient(handler)){
    client.BaseAddress = new Uri(BASE_URL);
    client.Timeout = new TimeSpan(0, 0, TIMEOUT_SECONDS);
    HttpRequestHeaders headers = client.DefaultRequestHeaders;
    headers.Add("X-User", Environment.UserName);
    headers.Add("Accept-Encoding", "br"); //gzip
    HttpResponseMessage response = null;

    response = await client.GetAsync($"{requestUrl}");
    if (response.IsSuccessStatusCode)
    {
        string strResult = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(strResult);
    }
}

strResult不是JSON..

The strResult is not JSON. . .

推荐答案

假定您使用的是.NET Core 2.1中包含的HttpClientFactory,那么您可以创建一个委托处理程序,该处理程序将在交付完整有效负载之前对其进行拦截和解压缩到您的代码.

Assuming you are using the HttpClientFactory that was included in .NET Core 2.1 then you can just create a delegating handler which will intercept and decompress it before handing the full payload to your code.

using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using BrotliSharpLib;

public class BrotliCompressionHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);
        if (!response.Content.Headers.TryGetValues("Content-Encoding", out var ce) || ce.First() != "br")
            return response;
        var buffer = await response.Content.ReadAsByteArrayAsync();
        response.Content = new ByteArrayContent(Brotli.DecompressBuffer(buffer, 0, buffer.Length));
        return response;
    }
}

然后将处理程序连接到需要支持brotli的客户端.

Then just wire up the handler to the client(s) you need to support brotli with.

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddTransient<BrotliCompressionHandler>()
        .AddHttpClient("github", c =>
        {
            c.BaseAddress = new Uri("https://api.github.com/");
            c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
            c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
        })
        .AddHttpMessageHandler<BrotliCompressionHandler>();
}

这篇关于在HttpClient中解压缩Brotli HttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆