是否可以使HttpClient在响应中忽略无效的ETag标头? [英] Is it possible to make HttpClient ignore invalid ETag header in response?

查看:203
本文介绍了是否可以使HttpClient在响应中忽略无效的ETag标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,该应用程序使用HttpClient API向无法控制的第三方服务发出Web服务请求.该服务似乎使用ETag HTTP标头响应请求,该标头包含根据HTTP规范的无效值(该值未用引号引起来).这会导致HttpClient失败,并显示System.FormatException.

I'm working on an application which makes a web service request using the HttpClient API to a third party service over which I have no control. The service seems to respond to requests with an ETag HTTP header containing an invalid value according to the HTTP specification (the value is not enclosed in quotation marks). This causes the HttpClient to fail with a System.FormatException.

在这种情况下,我对ETag标头不感兴趣,并且希望能够忽略无效值. 是否可以使用HttpClient来做到这一点?

In this case I am not interested in the ETag header and would like to be able to ignore the invalid value. Is it possible to do this using HttpClient?

相对于WebClientWebRequest,我更喜欢使用HttpClient API,因为这种特殊的用例要求我使用SOCKS代理,这在使用HttpClient时要简单得多.

I would prefer to use the HttpClient API over WebClient or WebRequest since this particular use case requires me to use a SOCKS proxy which is a lot simpler when using HttpClient.

推荐答案

尝试一下:

class Example
{
    static void Main()
    {
        var client = HttpClientFactory.Create(new Handler());
        client.BaseAddress = new Uri("http://www.example.local");
        var r = client.GetAsync("").Result;
        Console.WriteLine(r.StatusCode);
        Console.WriteLine(r.Headers.ETag);
    }
}

class Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var headerName = "ETag";
        var r = await base.SendAsync(request, cancellationToken);
        var header = r.Headers.FirstOrDefault(x => x.Key == headerName);
        var updatedValue = header.Value.Select(x => x.StartsWith("\"") ? x : "\"" + x + "\"").ToList();
        r.Headers.Remove(headerName);
        r.Headers.Add(headerName, updatedValue);
        return r;
    }
}

我的响应标题:

HTTP/1.1 200确定

HTTP/1.1 200 OK

日期:2013年1月25日星期五,格林尼治标准时间

Date: Fri, 25 Jan 2013 16:49:29 GMT

FiddlerTemplate:正确

FiddlerTemplate: True

内容长度:310

内容类型:图片/gif

Content-Type: image/gif

ETag:rtt123

ETag: rtt123

这篇关于是否可以使HttpClient在响应中忽略无效的ETag标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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