Package org.apache.http.impl.client

Examples of org.apache.http.impl.client.HttpClientBuilder


        Scheme scheme = new Scheme(HTTPS, port, socketFactory);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(scheme);

        HttpClientBuilder builder = HttpClientBuilder.create();


        DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry));
        httpClient.getParams().setParameter(ClientPNames.DEFAULT_HOST,
            new HttpHost(url.getHost(), url.getPort(), url.getProtocol()));


        if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
          httpClient.getCredentialsProvider().setCredentials(
              new AuthScope(url.getHost(), port),
              new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME), line.getOptionValue(RDAPOptions.PASSWORD)));

          BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
          credentialsProvider.setCredentials(
              new AuthScope(url.getHost(), port),
              new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME), line.getOptionValue(RDAPOptions.PASSWORD)));
          builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HashSet<Header> headers = new HashSet<Header>();
        headers.add(new BasicHeader("Accept-Language", line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));

        httpClient.getParams().setParameter(ClientPNames.DEFAULT_HEADERS, headers);
        builder.setDefaultHeaders(Collections.singleton(new BasicHeader("Accept-Language", line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString()))));

        RDAPClient rdapClient = new RDAPClient(httpClient);
        if (line.hasOption(RDAPOptions.RAW)) {
          ObjectMapper mapper = new ObjectMapper();
          System.out.println(mapper.writer().writeValueAsString(rdapClient.getDomainAsJson(query)));
View Full Code Here


   * Instantiates a new apache http client.
   *
   */
  private ApacheHttpClient() {
   
    final HttpClientBuilder builder = HttpClientBuilder.create();
   
    // Allow self-signed SSL certificates:
    try {
      final SSLContextBuilder sslbuilder = new SSLContextBuilder();
      sslbuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
      final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
          sslbuilder.build(),
          SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     
      builder.setSSLSocketFactory(sslsf);
    } catch (final Exception e) {
      LOG.log(Level.WARNING, "Couldn't init SSL strategy", e);
    }
    // Work with PoolingClientConnectionManager
    final HttpClientConnectionManager connection = new PoolingHttpClientConnectionManager();
    builder.setConnectionManager(connection);
   
    // Provide eviction thread to clear out stale threads.
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          while (true) {
            synchronized (this) {
              wait(5000);
              connection.closeExpiredConnections();
              connection.closeIdleConnections(30,
                  TimeUnit.SECONDS);
            }
          }
        } catch (final InterruptedException ex) {
        }
      }
    }).start();
   
    try {
      builder.setDefaultCookieStore(new MyCookieStore());
    } catch (final IOException e) {
      LOG.log(Level.WARNING, "Couldn't init cookie store", e);
    }
   
    final RequestConfig globalConfig = RequestConfig.custom()
        .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
        .setConnectTimeout(20000).setStaleConnectionCheckEnabled(false)
        .build();
   
    builder.setDefaultRequestConfig(globalConfig);
   
    final SocketConfig socketConfig = SocketConfig.custom()
        .setSoTimeout(60000).setTcpNoDelay(true).build();
    builder.setDefaultSocketConfig(socketConfig);
   
    // generate httpclient
    httpClient = builder.build();
  }
View Full Code Here

  @Override
  public synchronized HttpClient getHttpClient() {
    if (myHttpClient == null) {
      PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
      HttpClientBuilder builder = HttpClientBuilder.create();
      builder.setConnectionManager(connectionManager);
      myHttpClient = builder.build();
    }
    return myHttpClient;
  }
View Full Code Here

  protected CloseableHttpClient createHttpClient(GoogleAnalyticsConfig config) {
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(Math.min(config.getMaxThreads(), 1));

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager);

    if (isNotEmpty(config.getUserAgent())) {
      builder.setUserAgent(config.getUserAgent());
    }

    if (isNotEmpty(config.getProxyHost())) {
      builder.setProxy(new HttpHost(config.getProxyHost(), config.getProxyPort()));

      if (isNotEmpty(config.getProxyUserName())) {
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
            new UsernamePasswordCredentials(config.getProxyUserName(), config.getProxyPassword()));
        builder.setDefaultCredentialsProvider(credentialsProvider);
      }
    }

    return builder.build();
  }
View Full Code Here

    // ====================================================================================================

    // HttpClient to use
    private HttpClient createHttpClient(String certPath) throws DockerAccessException {
        HttpClientBuilder builder = HttpClients.custom();
        addSslSupportIfNeeded(builder,certPath);

        // TODO: Tune client if needed (e.g. add pooling factoring .....
        // But I think, that's not really required.

        return builder.build();
    }
View Full Code Here

    /**
     * Posts a file to the git repository
     */
    public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl, String branch, String path, Logger logger) throws URISyntaxException, IOException {
        HttpClientBuilder builder = HttpClients.custom();
        if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials(user, password));
            builder = builder
                    .setDefaultCredentialsProvider(credsProvider);
        }

        CloseableHttpClient client = builder.build();
        try {

            String url = consoleUrl;
            if (!url.endsWith("/")) {
                url += "/";
View Full Code Here

        } catch (Exception e) {
            LOGGER.error("can't set TLS Support. Error is: {}", e, e);
        }

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
                .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
                .setMaxConnTotal(metadata.getMaxConnectionsTotal())
                .setDefaultRequestConfig(requestConfig)
                .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
                .setSslcontext(sslContext);

        if (!followRedirects) {
            httpClientBuilder.disableRedirectHandling();
        }

        httpClient = httpClientBuilder.build();

        httpAsyncClient = HttpAsyncClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
                .setMaxConnTotal(metadata.getMaxConnectionsTotal())
View Full Code Here

    }
   
  }
 
  protected HttpClient createSingleClient() {
    HttpClientBuilder client = HttpClients.custom().setDefaultRequestConfig(config);
   
    return client.build();
  }
View Full Code Here

     * the production code.
     * @return
     */
    private CloseableHttpClient createClient () {
        try {
            HttpClientBuilder builder = HttpClientBuilder.create();
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{getTrustManager()}, null);
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            builder.setSSLSocketFactory(scsf);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", scsf)
                    .build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
            return builder.build();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
View Full Code Here

        String doLogStr = servletConfig.getInitParameter(P_LOG);
        if (doLogStr != null) {
            this.doLog = Boolean.parseBoolean(doLogStr);
        }

        HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();

        if (System.getProperty(PROXY_ACCEPT_SELF_SIGNED_CERTS) != null) {
            acceptSelfSignedCerts = Boolean.parseBoolean(System.getProperty(PROXY_ACCEPT_SELF_SIGNED_CERTS));
        } else if (System.getenv(PROXY_ACCEPT_SELF_SIGNED_CERTS_ENV) != null) {
            acceptSelfSignedCerts = Boolean.parseBoolean(System.getenv(PROXY_ACCEPT_SELF_SIGNED_CERTS_ENV));
        }

        if (acceptSelfSignedCerts) {
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        return true;
                    }
                });
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                httpClientBuilder.setSSLSocketFactory(sslsf);
            } catch (NoSuchAlgorithmException e) {
                throw new ServletException(e);
            } catch (KeyStoreException e) {
                throw new ServletException(e);
            } catch (KeyManagementException e) {
                throw new ServletException(e);
            }
        }

        proxyClient = httpClientBuilder.build();
    }
View Full Code Here

TOP

Related Classes of org.apache.http.impl.client.HttpClientBuilder

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.