2 回答
TA贡献1895条经验 获得超3个赞
可以使用一个未记录的http.socket-factory-registry执行上下文属性来覆盖连接管理器在构造时设置的连接套接字工厂。
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setSSLContext(SSLContexts.createSystemDefault())
.build();
SSLContext customSSlContext = SSLContexts.custom()
.loadKeyMaterial(new File("my-keystore.jks"), "sectret".toCharArray(), "sectret".toCharArray())
.build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(customSSlContext))
.build();
HttpClientContext clientContext = HttpClientContext.create();
clientContext.setAttribute("http.socket-factory-registry", socketFactoryRegistry);
try (CloseableHttpResponse response = httpClient.execute(new HttpGet("https://host/stuff"), clientContext)) {
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
}
使用相同的客户端实例/相同的连接池来执行具有不同用户身份/安全上下文的多个线程的请求时要格外小心。
TA贡献1783条经验 获得超4个赞
我在这里发布我使用PoolingHttpClientConnectionManager类的解决方案,这个对我有用:
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier());
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslConnectionFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.setConnectionManager(cm)
.build();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
engine.setFollowRedirects(false);
ResteasyClient client = clientBuilder.httpEngine(engine).build();
ResteasyWebTarget target = client.target(UriBuilder.fromPath(
"https://my.server.com/mtls/protected/resource"));
String response = target.request().get(String.class);
添加回答
举报