Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:org.commonjava.util.jhttpc.HttpFactory.java

public CloseableHttpClient createClient(final SiteConfig location) throws JHttpCException {
    CloseableHttpClient client;/*from ww  w  .ja va  2 s . co m*/
    if (location != null) {
        HttpClientBuilder builder = HttpClients.custom();

        if (authenticator != null) {
            builder = authenticator.decorateClientBuilder(builder);
        }

        logger.debug("Using site config: {} for advanced client options", location);
        SiteConnectionConfig connConfig = new SiteConnectionConfig(location);

        final SSLConnectionSocketFactory sslFac = createSSLSocketFactory(location);
        if (sslFac != null) {
            //                HostnameVerifier verifier = new SSLHostnameVerifierImpl( );
            //                builder.setSSLHostnameVerifier( verifier );
            builder.setSSLSocketFactory(sslFac);
            connConfig.withSSLConnectionSocketFactory(sslFac);
        }

        ConnectionManagerTracker managerWrapper = connectionCache.getTrackerFor(connConfig);
        builder.setConnectionManager(managerWrapper.acquire());

        if (location.getProxyHost() != null) {
            final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(
                    new HttpHost(location.getProxyHost(), getProxyPort(location)));
            builder.setRoutePlanner(planner);
        }

        final int timeout = 1000 * location.getRequestTimeoutSeconds();
        builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout)
                .setSocketTimeout(timeout).setConnectTimeout(timeout).build());

        client = new TrackedHttpClient(builder.build(), managerWrapper);
        //            client = builder.build();
    } else {
        client = HttpClients.createDefault();
    }

    return client;
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

public TwidereHttpClientImpl(final Context context, final HttpClientConfiguration conf) {
    this.conf = conf;
    final HttpClientBuilder clientBuilder = HttpClients.custom();
    final LayeredConnectionSocketFactory factory = TwidereSSLSocketFactory.getSocketFactory(context,
            conf.isSSLErrorIgnored());/*from ww w .  j a v  a 2 s.c  o  m*/
    clientBuilder.setSSLSocketFactory(factory);
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setConnectTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(conf.getHttpReadTimeout());
    requestConfigBuilder.setRedirectsEnabled(false);
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    if (conf.isProxyConfigured()) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        clientBuilder.setProxy(proxy);
        if (!TextUtils.isEmpty(conf.getHttpProxyUser())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    client = clientBuilder.build();
}

From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;/*  w w w  .  ja v  a 2 s .com*/
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}

From source file:org.syncany.operations.init.ApplicationLink.java

private CloseableHttpClient createHttpClient() {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(2000)
            .setConnectTimeout(2000).setRedirectsEnabled(false);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // do we use a https proxy?
    String proxyHost = System.getProperty("https.proxyHost");
    String proxyPortStr = System.getProperty("https.proxyPort");
    String proxyUser = System.getProperty("https.proxyUser");
    String proxyPassword = System.getProperty("https.proxyPassword");

    if (proxyHost != null && proxyPortStr != null) {
        try {// w w w .  j  a va  2 s.com
            Integer proxyPort = Integer.parseInt(proxyPortStr);

            requestConfigBuilder.setProxy(new HttpHost(proxyHost, proxyPort));
            logger.log(Level.INFO, "Using proxy: " + proxyHost + ":" + proxyPort);

            if (proxyUser != null && proxyPassword != null) {
                logger.log(Level.INFO, "Proxy required credentials; using '" + proxyUser
                        + "' (username) and *** (hidden password)");

                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new UsernamePasswordCredentials(proxyUser, proxyPassword));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        } catch (NumberFormatException e) {
            logger.log(Level.WARNING, "Invalid proxy settings found. Not using proxy.", e);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    return httpClientBuilder.build();
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

@Override
public HttpClient createHTTPClient(String userAgent) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(createSSLContext());
    builder.setSchemePortResolver(createSchemePortResolver());
    builder.setDefaultRequestConfig(createRequestConfig());
    builder.setProxy(createProxy());// w  w w  .j av  a  2 s. c  o  m
    builder.setDefaultCredentialsProvider(createCredentialsProvider());
    builder.setDefaultConnectionConfig(createConnectionConfig());
    builder.setUserAgent(userAgent);
    builder.setMaxConnTotal(maxConnections);
    //builder.setMaxConnPerRoute(maxConnPerRoute)
    buildCustomHttpClient(builder);

    //TODO Put in place a more permanent solution to the following
    //Fix GitHub #17 start
    RedirectStrategy strategy = createRedirectStrategy();
    if (strategy == null) {
        strategy = LaxRedirectStrategy.INSTANCE;
    }
    builder.setRedirectStrategy(new TargetURLRedirectStrategy(strategy));
    //Fix end

    HttpClient httpClient = builder.build();
    if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) {
        authenticateUsingForm(httpClient);
    }
    return httpClient;
}

From source file:net.officefloor.plugin.web.http.application.WebApplicationAutoWireOfficeFloorSourceTest.java

@Override
protected void setUp() throws Exception {

    // Configure the port
    this.port = HttpTestUtil.getAvailablePort();
    this.source.getOfficeFloorCompiler().addProperty(
            HttpApplicationLocationManagedObjectSource.PROPERTY_HTTP_PORT, String.valueOf(this.port));
    HttpServerSocketManagedObjectSource.autoWire(this.source, this.port,
            WebApplicationAutoWireOfficeFloorSource.HANDLER_SECTION_NAME,
            WebApplicationAutoWireOfficeFloorSource.HANDLER_INPUT_NAME);

    // Configure the secure port
    this.securePort = HttpTestUtil.getAvailablePort();
    this.source.getOfficeFloorCompiler().addProperty(
            HttpApplicationLocationManagedObjectSource.PROPERTY_HTTPS_PORT, String.valueOf(this.securePort));
    HttpsServerSocketManagedObjectSource.autoWire(this.source, this.securePort,
            HttpTestUtil.getSslEngineSourceClass(),
            WebApplicationAutoWireOfficeFloorSource.HANDLER_SECTION_NAME,
            WebApplicationAutoWireOfficeFloorSource.HANDLER_INPUT_NAME);

    // Configure the HTTP Request State and HTTP Session
    this.source.addManagedObject(HttpRequestStateManagedObjectSource.class.getName(), processScopeWirer,
            new AutoWire(HttpRequestState.class));
    this.source.addManagedObject(HttpSessionManagedObjectSource.class.getName(), processScopeWirer,
            new AutoWire(HttpSession.class)).setTimeout(60 * 1000);

    // Configure the client (to not redirect)
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpTestUtil.configureHttps(builder);
    HttpTestUtil.configureNoRedirects(builder);
    this.client = builder.build();
}

From source file:com.floragunn.searchguard.ssl.AbstractUnitTest.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("node-0-keystore.jks")),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }//from   w  w  w .j  a  va 2  s.  c  o m

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main//from   w  ww  .jav  a 2  s . c o m
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java

protected HttpClient initHttpClient(ScimConnectorConfiguration conf) {
    HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

    if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
        HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBulder.setRoutePlanner(routePlanner);
    }//from w ww.jav a  2s  .  com

    HttpClient httpClient = httpClientBulder.build();

    return httpClient;
}

From source file:org.georchestra.security.Proxy.java

private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse,
        RequestType requestType, String sURL, boolean localProxy) {
    HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling();

    RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build();
    htb.setDefaultRequestConfig(config);

    ////w ww  . j  av a 2 s .co  m
    // Handle http proxy for external request.
    // Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128)
    htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    HttpClient httpclient = htb.build();

    HttpResponse proxiedResponse = null;
    int statusCode = 500;

    try {
        URL url = null;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) { // not an url
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }

        // HTTP protocol is required
        if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "HTTP protocol expected. \"" + url.getProtocol() + "\" used.");
            return;
        }

        // check if proxy must filter on final host
        if (!strategyForFilteringRequests.allowRequest(url)) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Host \"" + url.getHost() + "\" is not allowed to be requested");
            return;
        }

        logger.debug("Final request -- " + sURL);

        HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL);
        headerManagement.configureRequestHeaders(request, proxyingRequest);

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Header[] originalHeaders = proxyingRequest.getHeaders("sec-org");
            String org = "";
            for (Header originalHeader : originalHeaders) {
                org = originalHeader.getValue();
            }
            // no OGC SERVICE log if request going through /proxy/?url=
            if (!request.getRequestURI().startsWith("/sec/proxy/")) {
                String[] roles = new String[] { "" };
                try {
                    Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles");
                    if (rolesHeaders.length > 0) {
                        roles = rolesHeaders[0].getValue().split(";");
                    }
                } catch (Exception e) {
                    logger.error("Unable to compute roles");
                }
                statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles));

            }

        } catch (Exception e) {
            logger.error("Unable to log the request into the statistics logger", e);
        }

        if (localProxy) {
            //
            // Hack for geoserver
            // Should not be here. We must use a ProxyTarget class and
            // define
            // if Host header should be forwarded or not.
            //
            request.getHeader("Host");
            proxyingRequest.setHeader("Host", request.getHeader("Host"));

            if (logger.isDebugEnabled()) {
                logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue()
                        + " for proxy request.");
            }
        }
        proxiedResponse = executeHttpRequest(httpclient, proxyingRequest);
        StatusLine statusLine = proxiedResponse.getStatusLine();
        statusCode = statusLine.getStatusCode();
        String reasonPhrase = statusLine.getReasonPhrase();

        if (reasonPhrase != null && statusCode > 399) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase);
            }

            if (statusCode == 401) {
                //
                // Handle case of basic authentication.
                //
                Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate");
                finalResponse.setHeader("WWW-Authenticate",
                        (authHeader == null) ? "Basic realm=\"Authentication required\""
                                : authHeader.getValue());
            }

            // 403 and 404 are handled by specific JSP files provided by the
            // security-proxy webapp
            if ((statusCode == 404) || (statusCode == 403)) {
                finalResponse.sendError(statusCode);
                return;
            }
        }

        headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse,
                this.targets);

        if (statusCode == 302 || statusCode == 301) {
            adjustLocation(request, proxiedResponse, finalResponse);
        }
        // get content type

        String contentType = null;
        if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) {
            contentType = proxiedResponse.getEntity().getContentType().getValue();
            logger.debug("content-type detected: " + contentType);
        }

        // content type has to be valid
        if (isCharsetRequiredForContentType(contentType)) {
            doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType);
        } else {
            logger.debug("charset not required for contentType: " + contentType);
            doHandleRequest(request, finalResponse, requestType, proxiedResponse);
        }
    } catch (IOException e) {
        // connection problem with the host
        logger.error("Exception occured when trying to connect to the remote host: ", e);
        try {
            finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (IOException e2) {
            // error occured while trying to return the
            // "service unavailable status"
            finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}