How to update the settings of an HttpClient in httpclient 4.3+?

落爺英雄遲暮 提交于 2019-12-03 21:38:27

do something I have not proposed yet?

My recommendation would be to re-think the entire approach. One should not be removing / adding protocol interceptors at runtime but rather should be making use of HttpContext instance to update request execution context and pass configuration to protocol interceptors

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!