Search in sources :

Example 36 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project voltdb by VoltDB.

the class TestJSONInterface method httpUrlOverJSONExecute.

private static String httpUrlOverJSONExecute(String method, String url, String user, String password, String scheme, int expectedCode, String expectedCt, String varString) throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder hb = HttpClientBuilder.create();
    hb.setSslcontext(sslContext);
    hb.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = hb.build()) {
        HttpRequestBase request;
        switch(method) {
            case "POST":
                HttpPost post = new HttpPost(url);
                post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = post;
                break;
            case "PUT":
                HttpPut put = new HttpPut(url);
                put.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = put;
                break;
            case "DELETE":
                HttpDelete delete = new HttpDelete(url);
                request = delete;
                break;
            case "GET":
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
            default:
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
        }
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        request.setProtocolVersion(HttpVersion.HTTP_1_1);
        request.setConfig(rc);
        if (user != null && password != null) {
            if (scheme.equalsIgnoreCase("hashed")) {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("hashed256")) {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("basic")) {
                request.setHeader("Authorization", "Basic " + new String(Base64.encodeToString(new String(user + ":" + password).getBytes(), false)));
            }
        }
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                String ct = response.getHeaders("Content-Type")[0].getValue();
                if (expectedCt != null) {
                    assertTrue(ct.contains(expectedCt));
                }
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || HANDLED_CLIENT_ERRORS.contains(status)) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(request, rh);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) MessageDigest(java.security.MessageDigest) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 37 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project lucene-solr by apache.

the class HttpClientUtil method setupBuilder.

private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) {
    Builder requestConfigBuilder = RequestConfig.custom().setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false)).setDecompressionEnabled(false).setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT)).setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT));
    String cpolicy = cookiePolicy;
    if (cpolicy != null) {
        requestConfigBuilder.setCookieSpec(cpolicy);
    }
    RequestConfig requestConfig = requestConfigBuilder.build();
    HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig);
    if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) {
        retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(3));
    } else {
        retBuilder = retBuilder.setRetryHandler(NO_RETRY);
    }
    final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);
    if (basicAuthUser != null && basicAuthPass != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
        retBuilder.setDefaultCredentialsProvider(credsProvider);
    }
    if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) {
        retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    } else {
        retBuilder.disableContentCompression();
    }
    return retBuilder;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) RegistryBuilder(org.apache.http.config.RegistryBuilder) Builder(org.apache.http.client.config.RequestConfig.Builder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 38 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project sling by apache.

the class TopologyConnectorClient method createHttpClient.

private CloseableHttpClient createHttpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    // setting the SoTimeout (which is configured in seconds)
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(1000 * config.getSoTimeout()).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return builder.build();
}
Also used : DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Example 39 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project ddf by codice.

the class HttpSolrClientFactory method getSecureHttpClient.

private static CloseableHttpClient getSecureHttpClient(boolean retryRequestsOnError) {
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext(), getProtocols(), getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpRequestRetryHandler solrRetryHandler = new SolrHttpRequestRetryHandler();
    HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32);
    if (retryRequestsOnError) {
        builder.setRetryHandler(solrRetryHandler);
    }
    return builder.build();
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory)

Example 40 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project iTest by e-government-ua.

the class DeleteTask method createHttpClient_AcceptsUntrustedCerts.

public HttpClient createHttpClient_AcceptsUntrustedCerts() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSslcontext(sslContext);
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);
    HttpClient client = b.build();
    return client;
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpClient(org.apache.http.client.HttpClient) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)50 RequestConfig (org.apache.http.client.config.RequestConfig)17 HttpHost (org.apache.http.HttpHost)15 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)14 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)14 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)11 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)11 IOException (java.io.IOException)10 SSLContext (javax.net.ssl.SSLContext)10 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)10 CredentialsProvider (org.apache.http.client.CredentialsProvider)10 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)10 HttpClient (org.apache.http.client.HttpClient)8 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)8 HttpResponse (org.apache.http.HttpResponse)7 HttpGet (org.apache.http.client.methods.HttpGet)7 HttpPost (org.apache.http.client.methods.HttpPost)7 HttpContext (org.apache.http.protocol.HttpContext)7 AuthScope (org.apache.http.auth.AuthScope)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5