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

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#addInterceptorFirst() . 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: BmsHttpTransport.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
public BmsHttpTransport(HttpRequestInterceptor requestInterceptor) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE_CONNECTIONS);

    RequestConfig requestConfig = RequestConfig.custom().
            setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT).
            setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT).
            setSocketTimeout(DEFAULT_READ_TIMEOUT).
            build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().
            setConnectionManager(connectionManager).
            setDefaultRequestConfig(requestConfig).
            useSystemProperties();

    if (requestInterceptor != null) {
        httpClientBuilder.addInterceptorFirst(requestInterceptor);
    }

    this.httpClient = httpClientBuilder.build();
}
 
Example 2
Source File: HttpGetter.java    From commafeed with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient newClient(int timeout) {
	HttpClientBuilder builder = HttpClients.custom();
	builder.useSystemProperties();
	builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING);
	builder.disableAutomaticRetries();

	builder.setSSLContext(SSL_CONTEXT);
	builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

	RequestConfig.Builder configBuilder = RequestConfig.custom();
	configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
	configBuilder.setSocketTimeout(timeout);
	configBuilder.setConnectTimeout(timeout);
	configBuilder.setConnectionRequestTimeout(timeout);
	builder.setDefaultRequestConfig(configBuilder.build());

	builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build());

	return builder.build();
}
 
Example 3
Source File: HttpClientGenerator.java    From plumemo with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(connectionManager);
    if (site.getUserAgent() != null) {
        httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
        httpClientBuilder.setUserAgent("");
    }
    if (site.isUseGzip()) {
        httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

            @Override
            public void process(
                    HttpRequest request,
                    HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }
        });
    }
    //解决post/redirect/post 302跳转问题
    httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true).setTcpNoDelay(true);
    socketConfigBuilder.setSoTimeout(site.getTimeOut());
    SocketConfig socketConfig = socketConfigBuilder.build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    connectionManager.setDefaultSocketConfig(socketConfig);
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.build();
}
 
Example 4
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void setupClient() {
    final HttpClientBuilder clientBuilder = HttpClients.custom();

    if (sslContext != null) {
        clientBuilder.setSslcontext(sslContext);
        clientBuilder.addInterceptorFirst(new HttpsResponseInterceptor());
    }

    httpClient = clientBuilder
        .setDefaultCredentialsProvider(getCredentialsProvider()).build();
}
 
Example 5
Source File: JenkinsHttpClient.java    From jenkins-client-java with MIT License 5 votes vote down vote up
protected static HttpClientBuilder addAuthentication(HttpClientBuilder builder, URI uri, String username,
        String password) {
    if (isNotBlank(username)) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);
        builder.setDefaultCredentialsProvider(provider);

        builder.addInterceptorFirst(new PreemptiveAuth());
    }
    return builder;
}
 
Example 6
Source File: HttpClientGenerator.java    From zongtui-webcrawler with GNU General Public License v2.0 5 votes vote down vote up
private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager);
    if (site != null && site.getUserAgent() != null) {
        httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
        httpClientBuilder.setUserAgent("");
    }
    if (site == null || site.isUseGzip()) {
        httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

            public void process(
                    final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }

            }
        });
    }
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    if (site != null) {
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    }
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.build();
}
 
Example 7
Source File: HttpClientExample.java    From jbrotli with Apache License 2.0 5 votes vote down vote up
public String downloadFileAsString(String url) throws IOException {
  BrotliLibraryLoader.loadBrotli();
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.addInterceptorFirst(httpRequestInterceptor);
  httpClientBuilder.addInterceptorFirst(httpResponseInterceptor);
  try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
    String entity = downloadFileAsString(httpClient, url);
    if (entity != null) return entity;
  }
  return null;
}
 
Example 8
Source File: JolokiaClientFactory.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(HttpClientBuilder pBuilder, String pUser, String pPassword) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(pUser, pPassword));
    pBuilder.setDefaultCredentialsProvider(credentialsProvider);
    pBuilder.addInterceptorFirst(new PreemptiveAuthInterceptor(new BearerScheme()));
}
 
Example 9
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    RequestConfig.Builder requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
            .setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
    client.setDefaultRequestConfig(requestConfig.build());

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
    }

    return client;
}
 
Example 10
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void setupClient() {
    final HttpClientBuilder clientBuilder = HttpClients.custom();

    if (sslContext != null) {
        clientBuilder.setSSLContext(sslContext);
        clientBuilder.addInterceptorFirst(new HttpsResponseInterceptor());
    }

    httpClient = clientBuilder
        .setDefaultCredentialsProvider(getCredentialsProvider()).build();
}
 
Example 11
Source File: TraceeHttpInterceptorsIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testWritesToServerAndParsesResponse() throws IOException {

	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	httpClientBuilder.addInterceptorLast(new TraceeHttpRequestInterceptor());
	httpClientBuilder.addInterceptorFirst(new TraceeHttpResponseInterceptor());
	CloseableHttpClient httpClient = httpClientBuilder.build();

	HttpGet getMethod = new HttpGet(serverEndpoint);
	Tracee.getBackend().put("before Request", "yip");
	final HttpResponse response = httpClient.execute(getMethod);

	assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_NO_CONTENT));
	assertThat(Tracee.getBackend().get("responseFromServer"), equalTo("yes Sir"));
}
 
Example 12
Source File: HttpClientGenerator.java    From webmagic with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(connectionManager);
    if (site.getUserAgent() != null) {
        httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
        httpClientBuilder.setUserAgent("");
    }
    if (site.isUseGzip()) {
        httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

            public void process(
                    final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }
        });
    }
    //解决post/redirect/post 302跳转问题
    httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true).setTcpNoDelay(true);
    socketConfigBuilder.setSoTimeout(site.getTimeOut());
    SocketConfig socketConfig = socketConfigBuilder.build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    connectionManager.setDefaultSocketConfig(socketConfig);
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.build();
}
 
Example 13
Source File: JolokiaKubernetesAuthenticator.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(HttpClientBuilder httpClientBuilder, String s, String s1) {
    httpClientBuilder.addInterceptorFirst(new BearerTokenInterceptor(kubernetes.getConfiguration().getRequestConfig().getOauthToken()));
}
 
Example 14
Source File: ApacheHttpClientFactory.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public ConnectionManagerAwareHttpClient create(HttpClientSettings settings) {
    final HttpClientBuilder builder = HttpClients.custom();
    // Note that it is important we register the original connection manager with the
    // IdleConnectionReaper as it's required for the successful deregistration of managers
    // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
    final HttpClientConnectionManager cm = cmFactory.create(settings);

    builder.setRequestExecutor(new SdkHttpRequestExecutor())
            .setKeepAliveStrategy(buildKeepAliveStrategy(settings))
            .disableRedirectHandling()
            .disableAutomaticRetries()
            .setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

    // By default http client enables Gzip compression. So we disable it
    // here.
    // Apache HTTP client removes Content-Length, Content-Encoding and
    // Content-MD5 headers when Gzip compression is enabled. Currently
    // this doesn't affect S3 or Glacier which exposes these headers.
    //
    if (!(settings.useGzip())) {
        builder.disableContentCompression();
    }

    HttpResponseInterceptor itcp = new CRC32ChecksumResponseInterceptor();
    if (settings.calculateCRC32FromCompressedData()) {
        builder.addInterceptorFirst(itcp);
    } else {
        builder.addInterceptorLast(itcp);
    }

    addProxyConfig(builder, settings);

    final ConnectionManagerAwareHttpClient httpClient = new SdkHttpClient(builder.build(), cm);

    if (settings.useReaper()) {
        IdleConnectionReaper.registerConnectionManager(cm, settings.getMaxIdleConnectionTime());
    }

    return httpClient;
}
 
Example 15
Source File: HttpClientUtil.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) {
 
  Builder requestConfigBuilder = RequestConfig.custom()
      .setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false)).setDecompressionEnabled(false)
      .setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT))
      .setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT));

  String cpolicy = cookiePolicy;
  if (cpolicy != null) {
    requestConfigBuilder.setCookieSpec(cpolicy);
  }
  
  RequestConfig requestConfig = requestConfigBuilder.build();
  
  HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig);

  if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) {
    retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(Integer.getInteger("solr.httpclient.retries", 3)));

  } else {
    retBuilder = retBuilder.setRetryHandler(NO_RETRY);
  }

  final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
  final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);
  
  if (basicAuthUser != null && basicAuthPass != null) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
    retBuilder.setDefaultCredentialsProvider(credsProvider);
  }
  
  if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) {
    retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
    retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
  } else {
    retBuilder.disableContentCompression();
  }

  return retBuilder;
}