org.apache.http.conn.socket.LayeredConnectionSocketFactory Java Examples
The following examples show how to use
org.apache.http.conn.socket.LayeredConnectionSocketFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpProtocolParent.java From dubbox with Apache License 2.0 | 6 votes |
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(); }
Example #2
Source File: ExtendedConnectionOperator.java From lavaplayer with Apache License 2.0 | 6 votes |
@Override public void upgrade(ManagedHttpClientConnection connection, HttpHost host, HttpContext context) throws IOException { ConnectionSocketFactory socketFactory = getSocketFactory(host, HttpClientContext.adapt(context)); if (!(socketFactory instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } LayeredConnectionSocketFactory layeredFactory = (LayeredConnectionSocketFactory) socketFactory; Socket socket = connection.getSocket(); int port = this.schemePortResolver.resolve(host); socket = layeredFactory.createLayeredSocket(socket, host.getHostName(), port, context); connection.bind(socket); }
Example #3
Source File: HttpProtocolParent.java From dtsopensource with Apache License 2.0 | 6 votes |
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(); }
Example #4
Source File: YouTrackClient.java From vk-java-sdk with MIT License | 5 votes |
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(); }
Example #5
Source File: GoogleApacheHttpTransport.java From google-api-java-client with Apache License 2.0 | 5 votes |
/** * Returns a new instance of {@link ApacheHttpTransport} that uses * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates. */ public static ApacheHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException { // Set socket buffer sizes to 8192 SocketConfig socketConfig = SocketConfig.custom() .setRcvBufSize(8192) .setSndBufSize(8192) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(-1, TimeUnit.MILLISECONDS); // Disable the stale connection check (previously configured in the HttpConnectionParams connectionManager.setValidateAfterInactivity(-1); // Use the included trust store KeyStore trustStore = GoogleUtils.getCertificateTrustStore(); SSLContext sslContext = SslUtils.getTlsSslContext(); SslUtils.initSslContext(sslContext, trustStore, SslUtils.getPkixTrustManagerFactory()); LayeredConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext); HttpClient client = HttpClientBuilder.create() .useSystemProperties() .setSSLSocketFactory(socketFactory) .setDefaultSocketConfig(socketConfig) .setMaxConnTotal(200) .setMaxConnPerRoute(20) .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .setConnectionManager(connectionManager) .disableRedirectHandling() .disableAutomaticRetries() .build(); return new ApacheHttpTransport(client); }
Example #6
Source File: HttpHelper.java From sputnik with Apache License 2.0 | 5 votes |
@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); } }
Example #7
Source File: MockSetup.java From cloudbreak with Apache License 2.0 | 5 votes |
private void disableSSLCheck() { try { SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); Unirest.setHttpClient(httpclient); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ignored) { throw new RuntimeException("can't create ssl settings"); } }
Example #8
Source File: SimpleHttpClientFactoryBean.java From springboot-shiro-cas-mybatis with MIT License | 4 votes |
/** * 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); } }
Example #9
Source File: HttpClientFactory.java From multiapps-controller with Apache License 2.0 | 4 votes |
public HttpClientFactory(LayeredConnectionSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; }
Example #10
Source File: HttpClientRestClient.java From pardot-java-client with MIT License | 4 votes |
/** * Initialization method. This takes in the configuration and sets up the underlying * http client appropriately. * @param configuration The user defined configuration. */ @Override public void init(final Configuration configuration) { // Save reference to configuration this.configuration = configuration; // Load RequestMutator instance from configuration. requestInterceptor = configuration.getRequestInterceptor(); // Create default SSLContext final SSLContext sslcontext = SSLContexts.createDefault(); // Initialize ssl context with configured key and trust managers. try { sslcontext.init(new KeyManager[0], getTrustManagers(), new SecureRandom()); } catch (final KeyManagementException exception) { throw new RuntimeException(exception.getMessage(), exception); } // Create hostname verifier instance. final HostnameVerifier hostnameVerifier; // Emit an warning letting everyone know we're using an insecure configuration. if (configuration.getIgnoreInvalidSslCertificates()) { logger.warn("Using insecure configuration, skipping server-side certificate validation checks."); // If we're configured to ignore invalid certificates, use the Noop verifier. hostnameVerifier = NoopHostnameVerifier.INSTANCE; } else { // Use default implementation hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } // Allow TLSv1_1 and TLSv1_2 protocols final LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier ); // Setup client builder final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder // Pardot disconnects requests after 120 seconds. .setConnectionTimeToLive(130, TimeUnit.SECONDS) .setSSLSocketFactory(sslsf); // Define our RequestConfigBuilder final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); // If we have a configured proxy host if (configuration.getProxyHost() != null) { // Define proxy host final HttpHost proxyHost = new HttpHost( configuration.getProxyHost(), configuration.getProxyPort(), configuration.getProxyScheme() ); // If we have proxy auth enabled if (configuration.getProxyUsername() != null) { // Create credential provider final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(configuration.getProxyHost(), configuration.getProxyPort()), new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword()) ); // Attach Credentials provider to client builder. clientBuilder.setDefaultCredentialsProvider(credsProvider); } // Attach Proxy to request config builder requestConfigBuilder.setProxy(proxyHost); } // Attach default request config clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); // build http client httpClient = clientBuilder.build(); }
Example #11
Source File: HttpClientFactory.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
public Builder withSslSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; }
Example #12
Source File: HttpClientFactoryTest.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
@Test public void builderSetsAllFields() { HttpClientFactory.Builder builder = new HttpClientFactory.Builder(); ConnectionSocketFactory plainSocketFactory = mock(ConnectionSocketFactory.class); LayeredConnectionSocketFactory sslSocketFactory = mock(LayeredConnectionSocketFactory.class); SchemeIOSessionStrategy httpIOSessionStrategy = mock(SchemeIOSessionStrategy.class); SchemeIOSessionStrategy httpsIOSessionStrategy = mock(SchemeIOSessionStrategy.class); CredentialsProvider credentialsProvider = mock(CredentialsProvider.class); builder.withServerList(TEST_SERVER_LIST) .withConnTimeout(TEST_CONNECTION_TIMEOUT) .withReadTimeout(TEST_READ_TIMEOUT) .withMaxTotalConnections(TEST_MAX_TOTAL_CONNECTIONS) .withIoThreadCount(TEST_IO_THREAD_COUNT) .withPooledResponseBuffers(TEST_POOLED_RESPONSE_BUFFERS_ENABLED) .withPooledResponseBuffersSizeInBytes(TEST_POOLED_RESPONSE_BUFFERS_SIZE_IN_BYTES) .withPlainSocketFactory(plainSocketFactory) .withSslSocketFactory(sslSocketFactory) .withHttpIOSessionStrategy(httpIOSessionStrategy) .withHttpsIOSessionStrategy(httpsIOSessionStrategy) .withDefaultCredentialsProvider(credentialsProvider); // when HttpClientFactory httpClientFactory = builder.build(); // then assertEquals(TEST_SERVER_LIST, httpClientFactory.serverList); assertEquals(TEST_CONNECTION_TIMEOUT, httpClientFactory.connTimeout); assertEquals(TEST_READ_TIMEOUT, httpClientFactory.readTimeout); assertEquals(TEST_MAX_TOTAL_CONNECTIONS, httpClientFactory.maxTotalConnections); assertEquals(TEST_IO_THREAD_COUNT, httpClientFactory.ioThreadCount); assertEquals(TEST_POOLED_RESPONSE_BUFFERS_ENABLED, httpClientFactory.pooledResponseBuffersEnabled); assertEquals(TEST_POOLED_RESPONSE_BUFFERS_SIZE_IN_BYTES, httpClientFactory.pooledResponseBuffersSizeInBytes); assertEquals(plainSocketFactory, httpClientFactory.plainSocketFactory); assertEquals(sslSocketFactory, httpClientFactory.sslSocketFactory); assertEquals(httpIOSessionStrategy, httpClientFactory.httpIOSessionStrategy); assertEquals(httpsIOSessionStrategy, httpClientFactory.httpsIOSessionStrategy); assertEquals(credentialsProvider, httpClientFactory.defaultCredentialsProvider); }
Example #13
Source File: HttpClientFactoryTest.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
@Test public void builderSetsDefaultFields() { HttpClientFactory.Builder builder = new HttpClientFactory.Builder(); ConnectionSocketFactory plainSocketFactory = mock(ConnectionSocketFactory.class); LayeredConnectionSocketFactory sslSocketFactory = mock(LayeredConnectionSocketFactory.class); SchemeIOSessionStrategy httpIOSessionStrategy = mock(SchemeIOSessionStrategy.class); SchemeIOSessionStrategy httpsIOSessionStrategy = mock(SchemeIOSessionStrategy.class); CredentialsProvider credentialsProvider = mock(CredentialsProvider.class); builder.withServerList(TEST_SERVER_LIST) .withConnTimeout(TEST_CONNECTION_TIMEOUT) .withReadTimeout(TEST_READ_TIMEOUT) .withMaxTotalConnections(TEST_MAX_TOTAL_CONNECTIONS) .withIoThreadCount(TEST_IO_THREAD_COUNT) .withPooledResponseBuffers(TEST_POOLED_RESPONSE_BUFFERS_ENABLED) .withPooledResponseBuffersSizeInBytes(TEST_POOLED_RESPONSE_BUFFERS_SIZE_IN_BYTES) .withPlainSocketFactory(plainSocketFactory) .withSslSocketFactory(sslSocketFactory) .withHttpIOSessionStrategy(httpIOSessionStrategy) .withHttpsIOSessionStrategy(httpsIOSessionStrategy) .withDefaultCredentialsProvider(credentialsProvider); // when HttpClientFactory httpClientFactory = builder.build(); // then assertEquals(TEST_SERVER_LIST, httpClientFactory.serverList); assertEquals(TEST_CONNECTION_TIMEOUT, httpClientFactory.connTimeout); assertEquals(TEST_READ_TIMEOUT, httpClientFactory.readTimeout); assertEquals(TEST_MAX_TOTAL_CONNECTIONS, httpClientFactory.maxTotalConnections); assertEquals(TEST_IO_THREAD_COUNT, httpClientFactory.ioThreadCount); assertEquals(TEST_POOLED_RESPONSE_BUFFERS_ENABLED, httpClientFactory.pooledResponseBuffersEnabled); assertEquals(TEST_POOLED_RESPONSE_BUFFERS_SIZE_IN_BYTES, httpClientFactory.pooledResponseBuffersSizeInBytes); assertNotNull(httpClientFactory.plainSocketFactory); assertNotNull(httpClientFactory.sslSocketFactory); assertNotNull(httpClientFactory.httpIOSessionStrategy); assertNotNull(httpClientFactory.httpsIOSessionStrategy); assertNotNull(httpClientFactory.defaultCredentialsProvider); }
Example #14
Source File: ApacheHttpClient.java From jiguang-java-client-common with MIT License | 4 votes |
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(); _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; }
Example #15
Source File: HttpClientUtils.java From onetwo with Apache License 2.0 | 4 votes |
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(); }