如何在httpclient 4.3+中更新HttpClient的设置?
在httpclient 4.3中,如果您尊重所有弃用,则必须使用HttpClientBuilder
( 此处提供文档)构建和配置HttpClient
。 这些方法是显式的,它们看起来很容易使用,并且HttpClient
的界面很清晰。 但也许有点太多了。
在我自己的情况下,我必须inheritanceSpring的HttpComponentsHttpInvokerRequestExecutor
( 此处的文档)。 因此,我可以轻松获取HttpClient
,但我对此对象的所有了解都是它实现了接口。
由于客户端已经构建,并且我对它的实现一无所知,我无法访问AbstractHttpClient
的setHttpRequestRetryHandler
或addRequestInterceptor
(虽然是的,我知道,它们已被弃用)。
那么,更新这个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();
- 什么是apache中的SchemeRegistry以及何时应该使用它?
- 如何在apache HttpClient上设置TLS版本
- javax.net.ssl.SSLPeerUnverifiedException:主机名与对等方提供的证书主题不匹配
- HttpClient 4.3.x,修复已弃用的代码以使用当前的HttpClient实现
- Apache Camel Http和SSL
- 在HTTPClient 4.1中使用文件和字符串进行多部分POST
- 如何在multithreading操作中使用HttpAsyncClient?
- 从Commons HttpClient迁移到HttpComponents Client
- java filechannel cpu用法随着时间的推移而增长