Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#setDefaultHeaders()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setDefaultHeaders() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RabbitMQHttpClient.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username, final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory, final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create().
            setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}
 
Example 2
Source File: ElasticSearchTransportFactory.java    From bender with Apache License 2.0 5 votes vote down vote up
private HttpClientBuilder addUserPassAuth(HttpClientBuilder cb, BasicHttpAuthConfig auth) {
  /*
   * Send auth via headers as the credentials provider method of auth does not work when using
   * SSL.
   */
  byte[] encodedAuth =
      Base64.encodeBase64((auth.getUsername() + ":" + auth.getPassword()).getBytes());
  String authHeader = "Basic " + new String(encodedAuth);

  cb.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.AUTHORIZATION, authHeader)));

  return cb;
}
 
Example 3
Source File: HttpFetch.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient initClient(Builder builder) {
  HttpClientBuilder b = builder.builder;
  b.setConnectionManager(manager);
  ImmutableSet<Header> headers = 
    builder.defaultHeaders.build();
  if (!headers.isEmpty())
    b.setDefaultHeaders(headers);
  if (builder.userAgent != null)
    b.setUserAgent(builder.userAgent);
  return b.build();
}
 
Example 4
Source File: HttpClientFactory.java    From vividus with Apache License 2.0 4 votes vote down vote up
@Override
public IHttpClient buildHttpClient(HttpClientConfig config)
{
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultHeaders(config.createHeaders());
    if (config.hasCookieStore())
    {
        builder.setDefaultCookieStore(config.getCookieStore());
    }
    if (config.hasCredentials())
    {
        AuthScope authScope = config.hasAuthScope() ? config.getAuthScope()
                : ClientBuilderUtils.DEFAULT_AUTH_SCOPE;
        CredentialsProvider credProvider = ClientBuilderUtils.createCredentialsProvider(authScope,
                config.getCredentials());
        builder.setDefaultCredentialsProvider(credProvider);
    }

    sslContextFactory.getSslContext(SSLConnectionSocketFactory.SSL, !config.isSslCertificateCheckEnabled())
            .ifPresent(builder::setSSLContext);

    if (!config.isSslHostnameVerificationEnabled())
    {
        builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }
    builder.setConnectionManager(config.getConnectionManager());
    builder.setMaxConnTotal(config.getMaxTotalConnections());
    builder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    builder.addInterceptorLast(config.getLastRequestInterceptor());
    builder.addInterceptorLast(config.getLastResponseInterceptor());
    builder.setRedirectStrategy(config.getRedirectStrategy());
    builder.setRetryHandler(config.getHttpRequestRetryHandler());
    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(config.getConnectionRequestTimeout());
    requestConfigBuilder.setConnectTimeout(config.getConnectTimeout());
    requestConfigBuilder.setCircularRedirectsAllowed(config.isCircularRedirectsAllowed());
    requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    Optional.ofNullable(config.getCookieSpec()).ifPresent(requestConfigBuilder::setCookieSpec);
    builder.setDefaultRequestConfig(requestConfigBuilder.build());
    builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT)
            .setSoTimeout(config.getSocketTimeout())
            .build());
    builder.setDnsResolver(config.getDnsResolver());

    HttpClient httpClient = new HttpClient();
    httpClient.setCloseableHttpClient(builder.build());
    if (config.hasBaseUrl())
    {
        httpClient.setHttpHost(HttpHost.create(config.getBaseUrl()));
    }
    httpClient.setSkipResponseEntity(config.isSkipResponseEntity());
    return httpClient;
}
 
Example 5
Source File: DatabricksRestClientImpl.java    From databricks-rest-client with Apache License 2.0 4 votes vote down vote up
protected void initClient(DatabricksServiceFactory.Builder builder) {

    HttpClientBuilder clientBuilder = HttpClients.custom().useSystemProperties()
        .setRetryHandler(retryHandler)
        .setServiceUnavailableRetryStrategy(retryStrategy)
        .setDefaultRequestConfig(createRequestConfig(builder));

    List<Header> headers = new ArrayList<>();
    if (isNotEmpty(builder.getToken())) {
      Header authHeader = new BasicHeader("Authorization", String.format("Bearer %s", builder.getToken()));
      headers.add(authHeader);
    } else { // password authorization
      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(
          new AuthScope(host, HTTPS_PORT),
          new UsernamePasswordCredentials(builder.getUsername(), builder.getPassword()));

      clientBuilder.setDefaultCredentialsProvider(credsProvider);

    }

    String userAgent = builder.getUserAgent();
    if (userAgent != null && userAgent.length() > 0) {
      Header userAgentHeader = new BasicHeader("User-Agent", userAgent);
      headers.add(userAgentHeader);
    }

    if (!headers.isEmpty()) {
      clientBuilder.setDefaultHeaders(headers);
    }

    try {
      SSLContext ctx = SSLContext.getDefault();
      // Allow TLSv1.2 protocol only
      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
          ctx,
          new String[]{"TLSv1.2"},
          null,
          SSLConnectionSocketFactory.getDefaultHostnameVerifier());
      clientBuilder = clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
      logger.error("", e);
    }

    client = clientBuilder.build(); //CloseableHttpClient

    url = String.format("https://%s/api/%s", host, apiVersion);
    mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
  }
 
Example 6
Source File: AbstractHttpTransportFactory.java    From bender with Apache License 2.0 4 votes vote down vote up
protected HttpClientBuilder getClientBuilder(boolean useSSL, String url,
    Map<String, String> stringHeaders, int socketTimeout) {

  HttpClientBuilder cb = HttpClientBuilder.create();

  /*
   * Setup SSL
   */
  if (useSSL) {
    /*
     * All trusting SSL context
     */
    try {
      cb.setSSLContext(getSSLContext());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    /*
     * All trusting hostname verifier
     */
    cb.setSSLHostnameVerifier(new HostnameVerifier() {
      public boolean verify(String s, SSLSession sslSession) {
        return true;
      }
    });
  }

  /*
   * Add default headers
   */
  ArrayList<BasicHeader> headers = new ArrayList<BasicHeader>(stringHeaders.size());
  stringHeaders.forEach((k, v) -> headers.add(new BasicHeader(k, v)));
  cb.setDefaultHeaders(headers);

  /*
   * Set socket timeout and transport threads
   */
  SocketConfig sc = SocketConfig.custom().setSoTimeout(socketTimeout).build();
  cb.setDefaultSocketConfig(sc);
  cb.setMaxConnPerRoute(this.config.getThreads());
  cb.setMaxConnTotal(this.config.getThreads());

  return cb;
}
 
Example 7
Source File: ApacheGatewayConnection.java    From vespa with Apache License 2.0 4 votes vote down vote up
public HttpClient createClient() {
    HttpClientBuilder clientBuilder;
    if (connectionParams.useTlsConfigFromEnvironment()) {
        clientBuilder = VespaHttpClientBuilder.create();
    } else {
        clientBuilder = HttpClientBuilder.create();
        if (connectionParams.getSslContext() != null) {
            setSslContext(clientBuilder, connectionParams.getSslContext());
        } else {
            SslContextBuilder builder = new SslContextBuilder();
            if (connectionParams.getPrivateKey() != null && connectionParams.getCertificate() != null) {
                builder.withKeyStore(connectionParams.getPrivateKey(), connectionParams.getCertificate());
            }
            if (connectionParams.getCaCertificates() != null) {
                builder.withTrustStore(connectionParams.getCaCertificates());
            }
            setSslContext(clientBuilder, builder.build());
        }
        if (connectionParams.getHostnameVerifier() != null) {
            clientBuilder.setSSLHostnameVerifier(connectionParams.getHostnameVerifier());
        }
        clientBuilder.setUserTokenHandler(context -> null); // https://stackoverflow.com/a/42112034/1615280
    }
    clientBuilder.setMaxConnPerRoute(1);
    clientBuilder.setMaxConnTotal(1);
    clientBuilder.setConnectionTimeToLive(connectionParams.getConnectionTimeToLive().getSeconds(), TimeUnit.SECONDS);
    clientBuilder.setUserAgent(String.format("vespa-http-client (%s)", Vtag.currentVersion));
    clientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(Headers.CLIENT_VERSION, Vtag.currentVersion)));
    clientBuilder.disableContentCompression();
    // Try to disable the disabling to see if system tests become stable again.
    // clientBuilder.disableAutomaticRetries();
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setSocketTimeout(0);
    if (connectionParams.getProxyHost() != null) {
        requestConfigBuilder.setProxy(new HttpHost(connectionParams.getProxyHost(), connectionParams.getProxyPort()));
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    log.fine("Creating HttpClient: " + " ConnectionTimeout "
                    + " SocketTimeout 0 secs "
                    + " proxyhost (can be null) " + connectionParams.getProxyHost()
                    + ":" + connectionParams.getProxyPort()
                    + (useSsl ? " using ssl " : " not using ssl")
    );
    return clientBuilder.build();
}