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:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java

private void buildHttpClient() {
    requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT)
            .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
          // By always trusting the ssl certificate
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override//from w ww.  j a va  2s.co  m
            public boolean isTrusted(final X509Certificate[] chain, String authType) {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        connRegistryBuilder.register("https", sslsf);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn("Exception thrown while trying to register https");
        LOGGER.debug("Stacktrace", e);
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent("Cognitio");

    httpClient = clientBuilder.build();
}

From source file:org.geosamples.utilities.HTTPClient.java

/**
 * This method relaxes SSL constraints because geosamples does not yet
 * provide certificate.//w w  w .  ja  va  2 s.  com
 *
 * @see <a href="http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/">Tom's Blog</a>
 * @return CloseableHttpClient
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 */
public static CloseableHttpClient clientWithNoSecurityValidation()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    SSLContext sslContext = null;

    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true)
            .build();

    clientBuilder.setSSLContext(sslContext);

    // don't check Hostnames, either.
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    clientBuilder.setConnectionManager(connMgr);

    CloseableHttpClient httpClient = clientBuilder.build();

    return httpClient;
}

From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java

@Override
public String call() throws IOException {
    String response = "";
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
        return response;
    }/*  w ww . j av  a 2  s.c  o  m*/

    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(AuthScope.ANY, credentials);

    HttpHost proxy = null;
    if (httpProxy != null && !httpProxy.isEmpty()) {
        try {
            URL url = new URL(httpProxy);
            proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
            if (altLogger != null) {
                altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage());
            }
        }
    }

    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultCredentialsProvider(credProvider);
    if (proxy != null) {
        builder.setProxy(proxy);
    }
    CloseableHttpClient httpClient = builder.build();

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase());
            if (altLogger != null) {
                altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase());
            }
        }
    } catch (Exception e) {
        logger.error("Failed to submit result to Gerrit", e);
        if (altLogger != null) {
            altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString());
        }
    }
    return response;
}

From source file:org.obiba.mica.core.service.AgateRestService.java

protected HttpClient createHttpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    try {/*from w  w w . j  a v  a2  s  .c om*/
        builder.setSSLSocketFactory(getSocketFactory());
        // if component not specified, will use the default

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }

    return builder.build();
}

From source file:org.hupo.psi.mi.psicquic.ws.SolrBasedPsicquicService.java

private HttpClient createHttpClient() {

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotalConnections);
    cm.setDefaultMaxPerRoute(defaultMaxConnectionsPerHost);
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(connectionTimeOut);
    requestBuilder = requestBuilder.setSocketTimeout(soTimeOut);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    builder.setConnectionManager(cm);// w  ww. j  a  va 2 s. c  om

    return builder.build();
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private CloseableHttpClient buildHttpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    return builder.build();
}

From source file:basedefense.client.version.ModificationVersionCheck.java

public ModificationVersionCheck() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableCookieManagement();/*www  .jav  a  2s.  c  o  m*/
    builder.disableRedirectHandling();

    builder.setUserAgent(String.format(USER_AGENT_PATTERN, BaseDefenseModification.getInstance().getVersion()));
    builder.setDefaultHeaders(Lists.newArrayList(new BasicHeader("Accept", "application/vnd.github.v3+json")));

    this.httpClient = builder.build();
}

From source file:eu.fusepool.p3.proxy.ProxyHandler.java

ProxyHandler(String targetBaseUri) {
    if (targetBaseUri.endsWith("/")) {
        this.targetBaseUri = targetBaseUri.substring(0, targetBaseUri.length() - 1);
    } else {/*from   w w  w  . ja  v a 2  s  . c  o m*/
        this.targetBaseUri = targetBaseUri;
    }
    final HttpClientBuilder hcb = HttpClientBuilder.create();
    hcb.setRedirectStrategy(new NeverRedirectStrategy());
    httpclient = hcb.build();
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

@Test
public void testGenericTarballDownload() throws Exception {
    // Generate some test content
    String path = contentGenerator.newArtifactPath("tar.gz");
    Map<String, byte[]> entries = new HashMap<>();
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));

    final File tgz = makeTarball(entries);

    System.out.println("tar content array has length: " + tgz.length());

    // We only need one repo server.
    ExpectationServer server = new ExpectationServer();
    server.start();//from  w ww .  j  a  v  a 2s  .  co m

    String url = server.formatUrl(path);

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.expect("GET", url, (req, resp) -> {
        //            Content-Length: 47175
        //            Content-Type: application/x-gzip
        resp.setHeader("Content-Encoding", "x-gzip");
        resp.setHeader("Content-Type", "application/x-gzip");

        byte[] raw = FileUtils.readFileToByteArray(tgz);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GzipCompressorOutputStream gzout = new GzipCompressorOutputStream(baos);
        gzout.write(raw);
        gzout.finish();

        byte[] content = baos.toByteArray();

        resp.setHeader("Content-Length", Long.toString(content.length));
        OutputStream respStream = resp.getOutputStream();
        respStream.write(content);
        respStream.flush();

        System.out.println("Wrote content with length: " + content.length);
    });

    final PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager();
    ccm.setMaxTotal(1);

    final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(ccm);
    CloseableHttpClient client = builder.build();

    HttpGet get = new HttpGet(url);
    //        get.setHeader( "Accept-Encoding", "gzip,deflate" );

    Boolean result = client.execute(get, (response) -> {
        Arrays.stream(response.getAllHeaders()).forEach((h) -> System.out.println("Header:: " + h));

        Header contentEncoding = response.getEntity().getContentEncoding();
        if (contentEncoding == null) {
            contentEncoding = response.getFirstHeader("Content-Encoding");
        }

        System.out.printf("Got content encoding: %s\n",
                contentEncoding == null ? "None" : contentEncoding.getValue());

        byte[] content = IOUtils.toByteArray(response.getEntity().getContent());

        try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new ByteArrayInputStream(content)))) {
            TarArchiveEntry entry = null;
            while ((entry = tarIn.getNextTarEntry()) != null) {
                System.out.printf("Got tar entry: %s\n", entry.getName());
                byte[] entryData = new byte[(int) entry.getSize()];
                int read = tarIn.read(entryData, 0, entryData.length);
            }
        }

        return false;
    });
}

From source file:gobblin.writer.http.AbstractHttpWriter.java

@SuppressWarnings("rawtypes")
public AbstractHttpWriter(AbstractHttpWriterBuilder builder) {
    super(builder.getState());
    this.log = builder.getLogger().isPresent() ? (Logger) builder.getLogger()
            : LoggerFactory.getLogger(this.getClass());
    this.debugLogEnabled = this.log.isDebugEnabled();

    HttpClientBuilder httpClientBuilder = builder.getHttpClientBuilder();
    httpClientBuilder.setConnectionManager(
            new HttpClientConnectionManagerWithConnTracking(builder.getHttpConnManager()));
    this.client = httpClientBuilder.build();
    this.singleThreadPool = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());

    if (builder.getSvcEndpoint().isPresent()) {
        setCurServerHost((URI) builder.getSvcEndpoint().get());
    }//  w  ww . ja v  a  2  s . c  o  m
}