Search in sources :

Example 51 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project rdf4j by eclipse.

the class HttpClientBuilders method getSSLTrustAllHttpClientBuilder.

/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all
 * certificates (particularly including self-signed certificates).
 *
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        HostnameVerifier hostNameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);
        return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
    } catch (Exception e) {
        // key management exception, etc.
        throw new RuntimeException(e);
    }
}
Also used : TrustStrategy(org.apache.http.ssl.TrustStrategy) SSLSession(javax.net.ssl.SSLSession) CertificateException(java.security.cert.CertificateException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509Certificate(java.security.cert.X509Certificate) CertificateException(java.security.cert.CertificateException) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 52 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project canal by alibaba.

the class HttpHelper method getIgnoreCerf.

private static String getIgnoreCerf(String url, CookieStore cookieStore, Map<String, String> params, int timeout) {
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    try {
        // 创建支持忽略证书的https
        final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(sslContext).setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build())).build();
        // ---------------- 创建支持https 的client成功---------
        URI uri = new URIBuilder(url).build();
        RequestConfig config = custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        httpGet = new HttpGet(uri);
        HttpClientContext context = HttpClientContext.create();
        context.setRequestConfig(config);
        response = httpClient.execute(httpGet, context);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg);
        }
    } catch (Throwable t) {
        long end = System.currentTimeMillis();
        long cost = end - start;
        String curlRequest = getCurlRequest(url, cookieStore, params, cost);
        throw new RuntimeException("requestPost(Https) remote error, request : " + curlRequest, t);
    } finally {
        long end = System.currentTimeMillis();
        long cost = end - start;
        printCurlRequest(url, null, null, cost);
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        if (httpGet != null) {
            httpGet.releaseConnection();
        }
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) SSLContext(javax.net.ssl.SSLContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) LoggerFactory(org.slf4j.LoggerFactory) HttpStatus(org.apache.http.HttpStatus) RequestConfig(org.apache.http.client.config.RequestConfig) EntityUtils(org.apache.http.util.EntityUtils) CookieStore(org.apache.http.client.CookieStore) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Map(java.util.Map) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) Cookie(org.apache.http.cookie.Cookie) URI(java.net.URI) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) RequestConfig.custom(org.apache.http.client.config.RequestConfig.custom) URIBuilder(org.apache.http.client.utils.URIBuilder) IOException(java.io.IOException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) NameValuePair(org.apache.http.NameValuePair) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) URIBuilder(org.apache.http.client.utils.URIBuilder) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder)

Example 53 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project canal by alibaba.

the class AbstractRequest method executeHttpRequest.

/**
 * 执行http请求
 *
 * @param getMethod
 * @return
 * @throws IOException
 */
@SuppressWarnings("deprecation")
private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry registry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf).build();
    HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
    CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnPerRoute(50).setMaxConnTotal(100).setConnectionManager(httpClientConnectionManager).build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    getMethod.setConfig(requestConfig);
    HttpResponse response = httpClient.execute(getMethod);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
        String result = EntityUtils.toString(response.getEntity());
        throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
    }
    return response;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) Registry(org.apache.http.config.Registry) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 54 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project java-chassis by ServiceComb.

the class HttpTransportFactory method getPoolingHttpClientConnectionManager.

private static PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager(SSLProperties sslProperties) {
    // register http/https socket factory
    RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create();
    builder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (sslProperties.isEnabled()) {
        builder.register("https", new SSLConnectionSocketFactory(SSLManager.createSSLContext(sslProperties.getSslOption(), sslProperties.getSslCustom()), NoopHostnameVerifier.INSTANCE));
    }
    Registry<ConnectionSocketFactory> connectionSocketFactoryRegistry = builder.build();
    // connection pool management
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_TOTAL);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
    return connectionManager;
}
Also used : ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 55 with SSLConnectionSocketFactory

use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project spring-framework by spring-projects.

the class ServerHttpsRequestIntegrationTests method startServer.

@BeforeEach
void startServer() throws Exception {
    this.server.setHandler(new CheckRequestHandler());
    this.server.afterPropertiesSet();
    this.server.start();
    // Set dynamically chosen port
    this.port = this.server.getPort();
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpclient);
    this.restTemplate = new RestTemplate(requestFactory);
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RestTemplate(org.springframework.web.client.RestTemplate) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)157 SSLContext (javax.net.ssl.SSLContext)99 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)63 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)54 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)52 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)49 IOException (java.io.IOException)42 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)42 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)42 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)31 KeyManagementException (java.security.KeyManagementException)30 RequestConfig (org.apache.http.client.config.RequestConfig)25 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)25 KeyStoreException (java.security.KeyStoreException)24 HttpClient (org.apache.http.client.HttpClient)24 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)24 KeyStore (java.security.KeyStore)22 CertificateException (java.security.cert.CertificateException)21 Test (org.junit.Test)21