如何在httpclient 4.3+中更新HttpClient的设置?

在httpclient 4.3中,如果您尊重所有弃用,则必须使用HttpClientBuilder ( 此处提供文档)构建和配置HttpClient 。 这些方法是显式的,它们看起来很容易使用,并且HttpClient的界面很清晰。 但也许有点太多了。

在我自己的情况下,我必须inheritanceSpring的HttpComponentsHttpInvokerRequestExecutor ( 此处的文档)。 因此,我可以轻松获取HttpClient ,但我对此对象的所有了解都是它实现了接口。

由于客户端已经构建,并且我对它的实现一无所知,我无法访问AbstractHttpClientsetHttpRequestRetryHandleraddRequestInterceptor (虽然是的,我知道,它们已被弃用)。

那么,更新这个HttpClient的设置最简洁的方法是什么(重试处理程序和请求拦截器是我目前最关心的那些)? 我是不是该…

  • …野蛮地将我的客户端投射到AbstractHttpClient ,希望我会一直收到这个实现?
  • …在我的HttpInvokerRequestExecutor的构造函数中创建一个新的HttpClient ,并获得类似下面的示例? 我可能会补充说Spring的构造函数(至少在3.2.4中)也使用了httpclient 4.3中不推荐使用的方法。 使用这种策略会不会有任何副作用?
  • ……做一些我还没有提出的建议吗?

自定义构造函数示例:

 public CustomHttpInvokerRequestExecutor() { super(); // will create an HttpClient // Now overwrite the client the super constructor created setHttpClient(HttpClientBuilder.custom(). ... .build()); } 

做一些我还没有提出的建议吗?

我的建议是重新思考整个方法。 不应该在运行时删除/添加协议拦截器,而应该使用HttpContext实例来更新请求执行上下文并将配置传递给协议拦截器

http://hc.apache.org/httpcomponents-core-4.4.x/tutorial/html/fundamentals.html#d5e306 http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fundamentals的.html#d5e223

 CloseableHttpClient client = HttpClientBuilder.create() .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { boolean b = (Boolean) context.getAttribute("my-config"); if (b) { // do something useful } } }) .build(); HttpClientContext context = HttpClientContext.create(); context.setAttribute("my-config", Boolean.TRUE); CloseableHttpResponse response1 = client.execute(new HttpGet("/"), context); response1.close(); context.setAttribute("my-config", Boolean.FALSE); CloseableHttpResponse response2 = client.execute(new HttpGet("/"), context); response2.close();