public void upgrade( final ManagedHttpClientConnection conn, final HttpHost host, final HttpContext context) throws IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); } if (!(sf instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; Socket sock = conn.getSocket(); final int port = this.schemePortResolver.resolve(host); sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); conn.bind(sock); }
/** * 获取LayeredConnectionSocketFactory 使用ssl单向认证 * * @date 2015年7月17日 * @return */ private LayeredConnectionSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
private HttpClient httpClient(JiraConnectionProperties jiraConnectionProperties) { try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial( jiraConnectionProperties.getSslTrustStore().getFile(), jiraConnectionProperties.getSslTrustStorePassword()) .build(); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(socketFactory, hostnameVerifier); if (jiraConnectionProperties.getSshJumpHost() != null) { sshProxy = new SshProxy(); sslSocketFactory = new SshTunnelSslSocketFactory(sshProxy, sslSocketFactory, jiraConnectionProperties.getSshJumpHost()); } return HttpClientBuilder.create() .setSSLSocketFactory(sslSocketFactory) .build(); } catch (GeneralSecurityException | IOException e) { throw new JiraSyncException("Failed to build custom http client", e); } }
private CloseableHttpClient createHttpClient(String hostname, int port) { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", plainsf).register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); // 将最大连接数增加 cm.setMaxTotal(maxTotal); // 将每个路由基础的连接增加 cm.setDefaultMaxPerRoute(maxPerRoute); HttpHost httpHost = new HttpHost(hostname, port); // 将目标主机的最大连接数增加 cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); // 请求重试处理 return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build(); }
@Override public void upgrade( final ManagedHttpClientConnection conn, final HttpHost host, final HttpContext context) throws IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); } if (!(sf instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; Socket sock = conn.getSocket(); final int port = this.schemePortResolver.resolve(host); sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); conn.bind(sock); }
/** * Create connection manager for http client. * * @return The connection manager for http client. */ private HttpClientConnectionManager createHttpClientConnectionManager() { ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslSocketFactory; try { sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(), SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { throw new BceClientException("Fail to create SSLConnectionSocketFactory", e); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register(Protocol.HTTP.toString(), socketFactory) .register(Protocol.HTTPS.toString(), sslSocketFactory).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections()); connectionManager .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(this.config.getSocketTimeoutInMillis()) .setTcpNoDelay(true).build()); connectionManager.setMaxTotal(this.config.getMaxConnections()); return connectionManager; }
public ConnectionManager() { loggedIn = false; SSLContext sslContext = SSLContexts.createSystemDefault(); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(); pcm.setMaxTotal(100); pcm.setDefaultMaxPerRoute(50); HttpCompressionRequestInterceptor requestInterceptor = new HttpCompressionRequestInterceptor(); HttpCompressionResponseInterceptor responseInterceptor = new HttpCompressionResponseInterceptor(); httpClient = HttpClients.custom() .setConnectionManager(pcm) .setSSLSocketFactory(sslSocketFactory) .addInterceptorFirst(requestInterceptor) .addInterceptorFirst(responseInterceptor) .build(); }
public JiraStatusEnum getIssueStatus(String statusId) { LayeredConnectionSocketFactory ssl = MethodBuilder.getSslSocketFactory(); try { JiraIssueWithStatusEntity issue = MethodBuilder.newGet(jiraUrl + "/issue/" + statusId + "?fields=status"). expectedCode(HttpStatus.SC_OK).withContentType(ContentType.APPLICATION_JSON) .withAuth(AuthBuilder.basic(username, password)).build().execute(JiraIssueWithStatusEntity.class); return issue.getFields().getStatus().getName(); } catch (MethodHttpException e) { LOGGER.error("Failed to get Jira issue - " + statusId, e); } return null; }
public JiraIssueEntity getIssue(String statusId) { LayeredConnectionSocketFactory ssl = MethodBuilder.getSslSocketFactory(); try { return MethodBuilder.newGet(jiraUrl + "/issue/" + statusId). expectedCode(HttpStatus.SC_OK).withContentType(ContentType.APPLICATION_JSON) .withAuth(AuthBuilder.basic(username, password)).build().execute(JiraIssueEntity.class); } catch (MethodHttpException e) { LOGGER.error("Failed to get Jira issue - " + statusId, e); } return null; }
public ExecutableMethodBuilder(ObjectMapper objectMapper, HttpRequestBase request, Auth auth, int expectedCode, LayeredConnectionSocketFactory sslSocketFactory) { this.objectMapper = objectMapper; this.request = request; this.expectedCode = expectedCode; this.auth = auth; setClient(sslSocketFactory); }
private synchronized void setClient(LayeredConnectionSocketFactory sslSocketFactory) { if (client == null) { client = HttpClientBuilder.create() .setSSLSocketFactory(sslSocketFactory) .build(); } }
private static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname, int port) { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory .getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory .getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( registry); // 将最大连接数增加 cm.setMaxTotal(maxTotal); // 将每个路由基础的连接增加 cm.setDefaultMaxPerRoute(maxPerRoute); // 将目标主机的最大连接数增加 HttpHost httpHost = new HttpHost(hostname, port); cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; }
public YouTrackClient(String host, String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword, String trustStoreType, String trustStorePath, String trustStorePassword) { this.host = host; CookieStore cookieStore = new BasicCookieStore(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SOCKET_TIMEOUT_MS) .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS) .setCookieSpec(CookieSpecs.STANDARD) .build(); LayeredConnectionSocketFactory sslFactory; RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()); if (host.contains("https://")) { try { sslFactory = initSslContext(keyStoreType, keyStorePath, keyStorePassword, keyPassword, trustStoreType, trustStorePath, trustStorePassword); registryBuilder.register("https", sslFactory); } catch (Exception e) { throw new IllegalStateException(e); } } Registry<ConnectionSocketFactory> registry = registryBuilder.build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS); client = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore) .build(); }
public CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname, int port) { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory .getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory .getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create().register("http", plainsf) .register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( registry); // 将最大连接数增加 cm.setMaxTotal(maxTotal); // 将每个路由基础的连接增加 cm.setDefaultMaxPerRoute(maxPerRoute); HttpHost httpHost = new HttpHost(hostname, port); // 将目标主机的最大连接数增加 cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= _maxRetryTimes) { return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext .adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler).build(); return httpClient; }
@SuppressWarnings("unchecked") @Before public void setup() throws Exception { conn = Mockito.mock(ManagedHttpClientConnection.class); socket = Mockito.mock(Socket.class); plainSocketFactory = Mockito.mock(ConnectionSocketFactory.class); sslSocketFactory = Mockito.mock(LayeredConnectionSocketFactory.class); socketFactoryRegistry = Mockito.mock(Lookup.class); schemePortResolver = Mockito.mock(SchemePortResolver.class); dnsResolver = Mockito.mock(DnsResolver.class); connectionOperator = new DefaultHttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); }
public Builder setUseSslWithCustomSSLSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) { if (sslSocketFactory == null) { throw new IllegalArgumentException("sslSocketFactory cannot be null"); } this.useSSL = true; this.customSSLSocketFactory = sslSocketFactory; return this; }
@Bean public HttpClient httpClient() { LOG.info("Using development (trust-self-signed) http client"); try { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r); RequestConfig requestConfig = RequestConfig .custom() .setSocketTimeout(30000) .setConnectTimeout(30000) .setTargetPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)) .setProxyPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)).build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, getUsernamePasswordCredentials()); return HttpClients.custom().setConnectionManager(cm) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(requestConfig).build(); } catch (Exception e) { throw new RuntimeException("Cannot build HttpClient using self signed certificate", e); } }
@Nullable public LayeredConnectionSocketFactory buildSSLSocketFactory(ConnectorDetails connectorDetails) { if (connectorDetails.isVerifySsl()) { return SSLConnectionSocketFactory.getSocketFactory(); } try { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUST_ALL_STRATEGY).build(); return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { log.error("Error building SSL socket factory", e); throw new IllegalStateException(e); } }
public static HttpClientConnectionManager getConnectionManager() { // ConnectionSocketFactory plainsf = null; LayeredConnectionSocketFactory sslsf = null; RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create(); PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); registryBuilder.register("http", plainsf); try { // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); HostnameVerifier allowAllHostnameVerifier = NoopHostnameVerifier.INSTANCE; sslsf = new SSLConnectionSocketFactory(sslcontext, allowAllHostnameVerifier); registryBuilder.register("https", sslsf); } catch (Throwable e) { logger.error("https ssl init failed", e); } Registry<ConnectionSocketFactory> r = registryBuilder.build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(r); connManager.setMaxTotal(100);// 连接池最大并发连接数 connManager.setDefaultMaxPerRoute(100);// 单路由最大并发数 return connManager; }
/** * Build a HTTP client based on the current properties. * * @return the built HTTP client */ private CloseableHttpClient buildHttpClient() { try { final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory; final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry); connMgmr.setMaxTotal(this.maxPooledConnections); connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute); connMgmr.setValidateAfterInactivity(DEFAULT_TIMEOUT); final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost()); final HttpRoute httpRoute = new HttpRoute(httpHost); connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE); final RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(this.readTimeout) .setConnectTimeout(this.connectionTimeout) .setConnectionRequestTimeout(this.connectionTimeout) .setCircularRedirectsAllowed(this.circularRedirectsAllowed) .setRedirectsEnabled(this.redirectsEnabled) .setAuthenticationEnabled(this.authenticationEnabled) .build(); final HttpClientBuilder builder = HttpClients.custom() .setConnectionManager(connMgmr) .setDefaultRequestConfig(requestConfig) .setSSLSocketFactory(sslsf) .setSSLHostnameVerifier(this.hostnameVerifier) .setRedirectStrategy(this.redirectionStrategy) .setDefaultCredentialsProvider(this.credentialsProvider) .setDefaultCookieStore(this.cookieStore) .setConnectionReuseStrategy(this.connectionReuseStrategy) .setConnectionBackoffStrategy(this.connectionBackoffStrategy) .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy) .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy) .setDefaultHeaders(this.defaultHeaders) .useSystemProperties(); return builder.build(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } }
/** * Build a HTTP client based on the current properties. * * @return the built HTTP client */ private CloseableHttpClient buildHttpClient() { try { final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory; final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry); connMgmr.setMaxTotal(this.maxPooledConnections); connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute); final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost()); final HttpRoute httpRoute = new HttpRoute(httpHost); connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE); final RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(this.readTimeout) .setConnectTimeout(this.connectionTimeout) .setConnectionRequestTimeout(this.connectionTimeout) .setStaleConnectionCheckEnabled(true) .setCircularRedirectsAllowed(this.circularRedirectsAllowed) .setRedirectsEnabled(this.redirectsEnabled) .setAuthenticationEnabled(this.authenticationEnabled) .build(); final HttpClientBuilder builder = HttpClients.custom() .setConnectionManager(connMgmr) .setDefaultRequestConfig(requestConfig) .setSSLSocketFactory(sslsf) .setSSLHostnameVerifier(this.hostnameVerifier) .setRedirectStrategy(this.redirectionStrategy) .setDefaultCredentialsProvider(this.credentialsProvider) .setDefaultCookieStore(this.cookieStore) .setConnectionReuseStrategy(this.connectionReuseStrategy) .setConnectionBackoffStrategy(this.connectionBackoffStrategy) .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy) .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy) .setDefaultHeaders(this.defaultHeaders) .useSystemProperties(); return builder.build(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } }
/** * Build a HTTP client based on the current properties. * * @return the built HTTP client */ private CloseableHttpClient buildHttpClient() { try { final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory; final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry); connMgmr.setMaxTotal(this.maxPooledConnections); connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute); connMgmr.setValidateAfterInactivity(DEFAULT_TIMEOUT); final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost()); final HttpRoute httpRoute = new HttpRoute(httpHost); connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE); final RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(this.readTimeout) .setConnectTimeout(Long.valueOf(this.connectionTimeout).intValue()) .setConnectionRequestTimeout(Long.valueOf(this.connectionTimeout).intValue()) .setCircularRedirectsAllowed(this.circularRedirectsAllowed) .setRedirectsEnabled(this.redirectsEnabled) .setAuthenticationEnabled(this.authenticationEnabled) .build(); final HttpClientBuilder builder = HttpClients.custom() .setConnectionManager(connMgmr) .setDefaultRequestConfig(requestConfig) .setSSLSocketFactory(sslsf) .setSSLHostnameVerifier(this.hostnameVerifier) .setRedirectStrategy(this.redirectionStrategy) .setDefaultCredentialsProvider(this.credentialsProvider) .setDefaultCookieStore(this.cookieStore) .setConnectionReuseStrategy(this.connectionReuseStrategy) .setConnectionBackoffStrategy(this.connectionBackoffStrategy) .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy) .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy) .setDefaultHeaders(this.defaultHeaders) .useSystemProperties(); return builder.build(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw Throwables.propagate(e); } }
public static void setSslSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) { MethodBuilder.sslSocketFactory = sslSocketFactory; }
public static LayeredConnectionSocketFactory getSslSocketFactory() { return sslSocketFactory; }
public SshTunnelSslSocketFactory(SshProxy sshProxy, LayeredConnectionSocketFactory connectionSocketFactory, String sshJumpHost) { this.sshProxy = sshProxy; this.connectionSocketFactory = connectionSocketFactory; this.sshJumpHost = sshJumpHost; }
private CloseableHttpClient wrapClient() { try { RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create(); ConnectionSocketFactory connectionSocketFactory = new PlainConnectionSocketFactory(); registryBuilder.register("http", connectionSocketFactory); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); TrustStrategy anyTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build(); LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registryBuilder.register("https", sslSF); Registry<ConnectionSocketFactory> registry = registryBuilder.build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); // 将最大连接数增加到200 cm.setMaxTotal(200); // 将每个路由基础的连接增加到20 cm.setDefaultMaxPerRoute(20); //请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) {// 如果已经重试了3次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return true; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(defaultRequestConfig) .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; } catch (Exception ex) { return null; } }
@Test public void testProxyConnectAndUpgrade() throws Exception { final HttpHost target = new HttpHost("somehost", 443, "https"); final HttpHost proxy = new HttpHost("someproxy", 8080); final InetAddress remote = InetAddress.getByAddress(new byte[] {10, 0, 0, 1}); final InetAddress local = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); final HttpRoute route = new HttpRoute(target, local, proxy, true); final CPoolEntry entry = new CPoolEntry(LogFactory.getLog(getClass()), "id", route, conn, -1, TimeUnit.MILLISECONDS); entry.markRouteComplete(); Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(conn.isOpen()).thenReturn(true); Mockito.when(future.isCancelled()).thenReturn(false); Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry); Mockito.when(pool.lease(route, null, null)).thenReturn(future); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(conn1); final ConnectionSocketFactory plainsf = Mockito.mock(ConnectionSocketFactory.class); final LayeredConnectionSocketFactory sslsf = Mockito.mock(LayeredConnectionSocketFactory.class); final Socket mockSock = Mockito.mock(Socket.class); final HttpClientContext context = HttpClientContext.create(); final SocketConfig sconfig = SocketConfig.custom().build(); final ConnectionConfig cconfig = ConnectionConfig.custom().build(); mgr.setDefaultSocketConfig(sconfig); mgr.setDefaultConnectionConfig(cconfig); Mockito.when(dnsResolver.resolve("someproxy")).thenReturn(new InetAddress[] {remote}); Mockito.when(schemePortResolver.resolve(proxy)).thenReturn(8080); Mockito.when(schemePortResolver.resolve(target)).thenReturn(8443); Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainsf); Mockito.when(socketFactoryRegistry.lookup("https")).thenReturn(sslsf); Mockito.when(plainsf.createSocket(Mockito.<HttpContext>any())).thenReturn(mockSock); Mockito.when(plainsf.connectSocket( Mockito.anyInt(), Mockito.eq(mockSock), Mockito.<HttpHost>any(), Mockito.<InetSocketAddress>any(), Mockito.<InetSocketAddress>any(), Mockito.<HttpContext>any())).thenReturn(mockSock); mgr.connect(conn1, route, 123, context); Mockito.verify(dnsResolver, Mockito.times(1)).resolve("someproxy"); Mockito.verify(schemePortResolver, Mockito.times(1)).resolve(proxy); Mockito.verify(plainsf, Mockito.times(1)).createSocket(context); Mockito.verify(plainsf, Mockito.times(1)).connectSocket(123, mockSock, proxy, new InetSocketAddress(remote, 8080), new InetSocketAddress(local, 0), context); Mockito.when(conn.getSocket()).thenReturn(mockSock); mgr.upgrade(conn1, route, context); Mockito.verify(schemePortResolver, Mockito.times(1)).resolve(target); Mockito.verify(sslsf, Mockito.times(1)).createLayeredSocket( mockSock, "somehost", 8443, context); mgr.routeComplete(conn1, route, context); }
private HttpClientSSLConfig(boolean useSSL, LayeredConnectionSocketFactory customSSLSocketFactory) { this.useSSL = useSSL; this.customSSLSocketFactory = customSSLSocketFactory; }
public LayeredConnectionSocketFactory getCustomSSLSocketFactory() { return customSSLSocketFactory; }
private static HttpClient createHttpClient0(CookieStore cookieStore) throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException{ RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create(); ConnectionSocketFactory http = new PlainConnectionSocketFactory(); registryBuilder.register("http", http); /*TrustManager trustManager = new X509TrustManager(){ @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; */ /*** * setConnectTimeout:设置连接超时时间,单位毫秒。 setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。 setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 */ RequestConfig reqConfig = createDefaultRequestConfig(); KeyStore trustStory = KeyStore.getInstance(KeyStore.getDefaultType()); TrustStrategy anyTrustStrategy = new TrustStrategy(){ @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom() .useProtocol("TLS") .loadTrustMaterial(trustStory, anyTrustStrategy) .build(); LayeredConnectionSocketFactory https = new SSLConnectionSocketFactory(sslContext); registryBuilder.register("https", https); Registry<ConnectionSocketFactory> registry = registryBuilder.build(); PoolingHttpClientConnectionManager poolMgr = new PoolingHttpClientConnectionManager(registry); return HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .setConnectionManager(poolMgr) .setDefaultRequestConfig(reqConfig) .build(); }
public TestObjectRemoteClient(String baseUrl, ProxySettings proxySettings) { X509HostnameVerifier defaultHostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SslConfigurator sslConfig = SslConfigurator.newInstance(); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslConfig.createSSLContext(), new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, defaultHostnameVerifier); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); ClientConfig config = new ClientConfig(); config.property(ApacheClientProperties.CONNECTION_MANAGER, new PoolingHttpClientConnectionManager(registry)); ApacheConnectorProvider connector = new ApacheConnectorProvider(); config.connectorProvider(connector); config.register(MultiPartFeature.class); config.register(JacksonFeature.class); if (proxySettings != null) { config.getProperties().put(ClientProperties.PROXY_URI, "http://" + proxySettings.getHost() + ":" + proxySettings.getPort()); if (proxySettings.getUsername() != null) { config.getProperties().put( ClientProperties.PROXY_USERNAME, proxySettings.getUsername() ); config.getProperties().put( ClientProperties.PROXY_PASSWORD, proxySettings.getPassword() ); } } SSLContext sslContext = sslConfig.createSSLContext(); client = ClientBuilder.newBuilder().sslContext(sslContext).newClient(config); WebTarget resource = client.target(baseUrl); user = new UserResourceImpl(resource); upload = new UploadResourceImpl(resource); appVersion = new AppVersionResourceImpl(resource); testSuite = new TestSuiteResourceImpl(resource); testSuiteReport = new TestSuiteReportResourceImpl(resource); qualityReport = new QualityReportResourceImpl(resource); deviceDescriptors = new DeviceDescriptorsResourceImpl(resource); sessionReport = new SessionReportResourceImpl(resource); testReportResource = new TestReportResourceImpl(resource); videoResource = new VideoResourceImpl(resource); }
/** * Sets a {@link LayeredConnectionSocketFactory} object to set connection properties, * such as supported SSL Protocols, hostname verifier, etc(needed to create a https connection). * * @param sslSocketFactory A {@link LayeredConnectionSocketFactory} object to get the connection properties from * @return this object */ public SafechargeClientBuilder setSSLSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; }
/** * Assigns {@link LayeredConnectionSocketFactory} instance. * <p/> * Please note this value can be overridden by the {@link #setConnectionManager( * org.apache.http.conn.HttpClientConnectionManager)} method. */ public final HttpClientBuilder setSSLSocketFactory( final LayeredConnectionSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; }
/** * Assigns {@link LayeredConnectionSocketFactory} instance. * <p> * Please note this value can be overridden by the {@link #setConnectionManager( * org.apache.http.conn.HttpClientConnectionManager)} method. * </p> */ public final HttpClientBuilder setSSLSocketFactory( final LayeredConnectionSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; }