Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients custom.

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:io.apicurio.studio.fe.servlet.servlets.DownloadServlet.java

@PostConstruct
protected void postConstruct() {
    try {/* w  w w .  j  a v a  2  s .  c o  m*/
        if (uiConfig.isDisableHubApiTrustManager()) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createSystem();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.wanghaomiao.seimi.http.hc.HttpClientFactory.java

public static HttpClientBuilder cliBuilder(int timeout) {
    HttpRequestRetryHandler retryHander = new HttpRequestRetryHandler() {
        @Override//from w  ww . j  a  v  a2 s  .  co  m
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof java.net.SocketTimeoutException) {
                //?
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return true;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }

            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };
    RedirectStrategy redirectStrategy = new SeimiRedirectStrategy();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout)
            .build();
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = HttpClientConnectionManagerProvider
            .getHcPoolInstance();
    return HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setConnectionManager(poolingHttpClientConnectionManager).setRedirectStrategy(redirectStrategy)
            .setRetryHandler(retryHander);
}

From source file:net.yacy.grid.http.ClientConnection.java

public final static CloseableHttpClient getClosableHttpClient() {
    return HttpClients.custom().useSystemProperties().setConnectionManager(getConnctionManager())
            .setDefaultRequestConfig(defaultRequestConfig).setMaxConnPerRoute(200).setMaxConnTotal(500).build();
}

From source file:org.cloudfoundry.identity.uaa.integration.FormLoginIntegrationTests.java

@Before
public void createHttpClient() throws Exception {
    httpclient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.DEFAULT).setDefaultHeaders(headers)
            .setDefaultCookieStore(cookieStore).build();
}

From source file:org.attribyte.api.http.impl.commons.Commons4Client.java

private void initFromOptions(final ClientOptions options) {

    if (options != ClientOptions.IMPLEMENTATION_DEFAULT) {

        HttpClientBuilder builder = HttpClients.custom();
        builder.setMaxConnTotal(options.maxConnectionsTotal);
        builder.setMaxConnPerRoute(options.maxConnectionsPerDestination);
        builder.setUserAgent(options.userAgent);
        if (options.proxyHost != null) {
            builder.setProxy(new HttpHost(options.proxyHost, options.proxyPort));
        }/*from   w  w w . j a  v  a  2s .  com*/

        this.defaultRequestConfig = RequestConfig.custom().setConnectTimeout(options.connectionTimeoutMillis)
                .setConnectionRequestTimeout(options.requestTimeoutMillis)
                .setRedirectsEnabled(RequestOptions.DEFAULT_FOLLOW_REDIRECTS)
                .setMaxRedirects(RequestOptions.DEFAULT_FOLLOW_REDIRECTS ? 5 : 0)
                .setAuthenticationEnabled(false).setCircularRedirectsAllowed(false)
                .setSocketTimeout(options.socketTimeoutMillis).build();
        builder.setDefaultRequestConfig(defaultRequestConfig);

        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setBufferSize(
                        options.requestBufferSize > options.responseBufferSize ? options.requestBufferSize
                                : options.responseBufferSize)
                .build();
        builder.setDefaultConnectionConfig(connectionConfig);

        this.httpClient = builder.build();
    } else {
        this.defaultRequestConfig = RequestConfig.DEFAULT;
        this.httpClient = HttpClients.createDefault();
    }
}

From source file:org.wso2.carbon.bpmn.extensions.rest.SyncInvokeTask.java

public SyncInvokeTask() {

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(200);//from  w w  w .ja v a  2 s  .c o  m
    cm.setMaxTotal(200);
    client = HttpClients.custom().setConnectionManager(cm).build();
}

From source file:org.hspconsortium.platform.launchcontext.LaunchOrchestrationEndpoint.java

@RequestMapping(value = "/smart/Launch", method = RequestMethod.POST)
public void handleLaunchRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String jsonString) {
    HttpPost postRequest = new HttpPost(this.authorizationServerLaunchEndpointURL);
    postRequest.addHeader("Content-Type", "application/json");
    StringEntity entity = null;/*from  w ww  .ja  v  a2s  .  c o m*/
    try {
        entity = new StringEntity(jsonString);
        postRequest.setEntity(entity);

        setAuthorizationHeader(postRequest, apiServerClientId, apiServerClientSecret);
    } catch (UnsupportedEncodingException uee_ex) {
        throw new RuntimeException(uee_ex);
    }

    CloseableHttpClient httpClient = HttpClients.custom().build();

    try (CloseableHttpResponse closeableHttpResponse = httpClient.execute(postRequest)) {
        if (closeableHttpResponse.getStatusLine().getStatusCode() != 200) {
            HttpEntity rEntity = closeableHttpResponse.getEntity();
            String responseString = EntityUtils.toString(rEntity, "UTF-8");
            throw new RuntimeException(String.format(
                    "There was a problem with the registration the Launch Context.\n"
                            + "Response Status : %s .\nResponse Detail :%s.",
                    closeableHttpResponse.getStatusLine(), responseString));
        }
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.getWriter().write(EntityUtils.toString(closeableHttpResponse.getEntity()));
    } catch (ClientProtocolException cpe_ex) {
        throw new RuntimeException(cpe_ex);
    } catch (IOException io_ex) {
        throw new RuntimeException(io_ex);
    }
}

From source file:com.microsoft.azure.hdinsight.common.task.YarnHistoryTask.java

@Override
public String call() throws Exception {
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .build();//from   w  w  w  .ja  v  a  2  s .c o m
    HttpGet httpGet = new HttpGet(path);
    httpGet.addHeader("Content-Type", "text/html");

    CloseableHttpResponse response = httpclient.execute(httpGet);

    HttpEntity httpEntity = response.getEntity();

    return IOUtils.toString(httpEntity.getContent());
}

From source file:com.ibm.watson.app.common.util.http.HttpClientBuilder.java

public static CloseableHttpClient buildDefaultHttpClient(Credentials cred) {

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    RequestConfig defaultRequestConfig;/*from  ww w  .java  2s.c om*/

    //private DefaultHttpClient client;
    connManager.setMaxTotal(200);
    connManager.setDefaultMaxPerRoute(50);
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // Create a registry of custom connection socket factories for supported
        // protocol schemes.
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(builder.build())).build();
    } catch (Exception e) {
        logger.warn(MessageKey.AQWEGA02000W_unable_init_ssl_context.getMessage(), e);
    }
    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.BASIC, AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setAuthenticationEnabled(true).build();

    if (cred != null)
        credentialsProvider.setCredentials(AuthScope.ANY, cred);

    return HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(defaultRequestConfig)
            .build();
}

From source file:com.rootcloud.ejb.RootCloudBean.java

private CloseableHttpClient createHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
    HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
    return HttpClients.custom().setSSLSocketFactory(connectionFactory).build();
}