org.apache.http.HttpRequestInterceptor Java Examples

The following examples show how to use org.apache.http.HttpRequestInterceptor. 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: ITTracingHttpAsyncClientBuilder.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void failedInterceptorRemovesScope() {
  assertThat(currentTraceContext.get()).isNull();
  RuntimeException error = new RuntimeException("Test");
  client = TracingHttpAsyncClientBuilder.create(httpTracing)
    .addInterceptorLast((HttpRequestInterceptor) (request, context) -> {
      throw error;
    }).build();
  client.start();

  assertThatThrownBy(() -> get(client, "/foo"))
    .isSameAs(error);

  assertThat(currentTraceContext.get()).isNull();

  testSpanHandler.takeRemoteSpanWithError(CLIENT, error);
}
 
Example #2
Source File: LayerHttpServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
	String baseUrl = (String) context.getAttribute(BASE_URL);
	String layerId = (String) context.getAttribute(LAYER_ID);
	try {
		if (interceptors != null && baseUrl != null) {
			for (Entry<String, List<HttpRequestInterceptor>> entry : interceptors.getMap().entrySet()) {
				String key = entry.getKey();
				if ("".equals(key) || (layerId != null && layerId.equals(key)) || baseUrl.startsWith(key)) {
					for (HttpRequestInterceptor inter : entry.getValue()) {
						inter.process(request, context);
					}
				}
			}
		}
	} catch (Exception e) {
		log.warn("Error processing interceptors: " + e.getMessage());
	}
}
 
Example #3
Source File: HttpClientUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
  // don't synchronize traversal - can lead to deadlock - CopyOnWriteArrayList is critical
  // we also do not want to have to acquire the mutex when the list is empty or put a global
  // mutex around the process calls
  interceptors.forEach(new Consumer<HttpRequestInterceptor>() {

    @Override
    public void accept(HttpRequestInterceptor interceptor) {
      try {
        interceptor.process(request, context);
      } catch (Exception e) {
        log.error("", e);
      }
    }
  });

}
 
Example #4
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 #5
Source File: Solr6Index.java    From atlas with Apache License 2.0 6 votes vote down vote up
private void configureSolrClientsForKerberos() throws PermanentBackendException {
    String kerberosConfig = System.getProperty("java.security.auth.login.config");
    if(kerberosConfig == null) {
        throw new PermanentBackendException("Unable to configure kerberos for solr client. System property 'java.security.auth.login.config' is not set.");
    }
    logger.debug("Using kerberos configuration file located at '{}'.", kerberosConfig);
    try(Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) {

        SolrHttpClientBuilder kb = krbBuild.getBuilder();
        HttpClientUtil.setHttpClientBuilder(kb);
        HttpRequestInterceptor bufferedEntityInterceptor = new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                if(request instanceof HttpEntityEnclosingRequest) {
                    HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
                    HttpEntity requestEntity = enclosingRequest.getEntity();
                    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
                }
            }
        };
        HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);

        HttpRequestInterceptor preemptiveAuth = new PreemptiveAuth(new KerberosScheme());
        HttpClientUtil.addRequestInterceptor(preemptiveAuth);
    }
}
 
Example #6
Source File: HttpWebConnection.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void configureHttpProcessorBuilder(final HttpClientBuilder builder, final WebRequest webRequest) {
    final HttpProcessorBuilder b = HttpProcessorBuilder.create();
    for (final HttpRequestInterceptor i : getHttpRequestInterceptors(webRequest)) {
        b.add(i);
    }

    // These are the headers used in HttpClientBuilder, excluding the already added ones
    // (RequestClientConnControl and RequestAddCookies)
    b.addAll(new RequestDefaultHeaders(null),
            new RequestContent(),
            new RequestTargetHost(),
            new RequestExpectContinue());
    b.add(new RequestAcceptEncoding());
    b.add(new RequestAuthCache());
    b.add(new ResponseProcessCookies());
    builder.setHttpProcessor(b.build());
}
 
Example #7
Source File: TomHttpClientGenerator.java    From tom-crawler 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 #8
Source File: HTTPSession.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HTTPUtil.InterceptRequest debugRequestInterceptor() {
  if (!TESTING)
    throw new UnsupportedOperationException();
  for (HttpRequestInterceptor hri : reqintercepts) {
    if (hri instanceof HTTPUtil.InterceptRequest)
      return ((HTTPUtil.InterceptRequest) hri);
  }
  return null;
}
 
Example #9
Source File: UrlSigningAuthConfig.java    From bender with Apache License 2.0 5 votes vote down vote up
public HttpRequestInterceptor getHttpInterceptor() {
  DefaultAWSCredentialsProviderChain cp = new DefaultAWSCredentialsProviderChain();

  AWS4Signer signer = new AWS4Signer();
  signer.setServiceName(this.service);
  signer.setRegionName(this.region.getName());

  return new AWSRequestSigningApacheInterceptor(this.service, signer, cp);
}
 
Example #10
Source File: WingtipsApacheHttpClientInterceptorTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void addTracingInterceptors_double_arg_works_as_expected(boolean subspanOptionOn) {
    // given
    HttpClientBuilder builder = HttpClientBuilder.create();

    // when
    addTracingInterceptors(builder, subspanOptionOn);

    // then
    HttpClientBuilderInterceptors builderInterceptors = new HttpClientBuilderInterceptors(builder);

    assertThat(builderInterceptors.firstRequestInterceptors).hasSize(1);
    assertThat(builderInterceptors.lastResponseInterceptors).hasSize(1);

    HttpRequestInterceptor requestInterceptor = builderInterceptors.firstRequestInterceptors.get(0);
    HttpResponseInterceptor responseInterceptor = builderInterceptors.lastResponseInterceptors.get(0);
    assertThat(requestInterceptor).isInstanceOf(WingtipsApacheHttpClientInterceptor.class);
    assertThat(responseInterceptor).isInstanceOf(WingtipsApacheHttpClientInterceptor.class);

    assertThat(((WingtipsApacheHttpClientInterceptor) requestInterceptor).surroundCallsWithSubspan)
        .isEqualTo(subspanOptionOn);
    assertThat(((WingtipsApacheHttpClientInterceptor) responseInterceptor).surroundCallsWithSubspan)
        .isEqualTo(subspanOptionOn);

    assertThat(builderInterceptors.lastRequestInterceptors).isNullOrEmpty();
    assertThat(builderInterceptors.firstResponseInterceptors).isNullOrEmpty();

    if (subspanOptionOn) {
        assertThat(builderInterceptors.firstRequestInterceptors).containsExactly(DEFAULT_REQUEST_IMPL);
        assertThat(builderInterceptors.lastResponseInterceptors).containsExactly(DEFAULT_RESPONSE_IMPL);
    }
}
 
Example #11
Source File: WingtipsApacheHttpClientInterceptorTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
public HttpClientBuilderInterceptors(HttpClientBuilder builder) {
    this.firstRequestInterceptors =
        (List<HttpRequestInterceptor>) Whitebox.getInternalState(builder, "requestFirst");
    this.lastRequestInterceptors =
        (List<HttpRequestInterceptor>) Whitebox.getInternalState(builder, "requestLast");
    this.firstResponseInterceptors =
        (List<HttpResponseInterceptor>) Whitebox.getInternalState(builder, "responseFirst");
    this.lastResponseInterceptors =
        (List<HttpResponseInterceptor>) Whitebox.getInternalState(builder, "responseLast");
}
 
Example #12
Source File: DcosHttpClientBuilder.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Assigns a token provider which will produce HTTP auth tokens to be included in requests.
 *
 * @return this
 */
public DcosHttpClientBuilder setTokenProvider(TokenProvider provider) {
  this.addInterceptorFirst(
      (HttpRequestInterceptor) (request, context) ->
          request.addHeader(
              "Authorization",
              String.format("token=%s", provider.getToken().getToken())));
  return this;
}
 
Example #13
Source File: HttpClientFactory.java    From riptide with MIT License 5 votes vote down vote up
public static CloseableHttpClient createHttpClient(final Client client,
        final List<HttpRequestInterceptor> firstRequestInterceptors,
        final HttpClientConnectionManager connectionManager,
        @Nullable final HttpClientCustomizer customizer,
        @Nullable final Object cacheStorage) {

    final Caching caching = client.getCaching();
    final HttpClientBuilder builder = caching.getEnabled() ?
            configureCaching(caching, cacheStorage) :
            HttpClientBuilder.create();

    final RequestConfig.Builder config = RequestConfig.custom();

    firstRequestInterceptors.forEach(builder::addInterceptorFirst);

    final Connections connections = client.getConnections();
    config.setConnectionRequestTimeout((int) connections.getLeaseRequestTimeout().to(MILLISECONDS));
    config.setConnectTimeout((int) connections.getConnectTimeout().to(MILLISECONDS));
    config.setSocketTimeout((int) connections.getSocketTimeout().to(MILLISECONDS));

    builder.setConnectionManager(connectionManager);
    builder.setDefaultRequestConfig(config.build());
    builder.disableAutomaticRetries();

    Optional.ofNullable(customizer).ifPresent(customize(builder));

    return builder.build();
}
 
Example #14
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 #15
Source File: WebRealmServiceTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
    throws IOException
{
    DefaultHttpClient client = new DefaultHttpClient();

    // Our request method
    HttpGet get = new HttpGet( "http://127.0.0.1:" + port + "/" );

    HttpResponse response = client.execute( get );
    int status = response.getStatusLine().getStatusCode();

    assertThat( String.valueOf( status ).substring( 0, 1 ) + "xx", is( "4xx" ) );

    EntityUtils.consume( response.getEntity() );

    // Simple interceptor set as first interceptor in the protocol chain
    HttpRequestInterceptor preemptiveAuth = new BasicAuthRequestInterceptor();
    client.addRequestInterceptor( preemptiveAuth, 0 );

    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials( "foo", "bar" );
    client.getCredentialsProvider().setCredentials( AuthScope.ANY, creds );

    response = client.execute( get );
    status = response.getStatusLine().getStatusCode();

    assertThat( status, is( 200 ) );

    String result = new BasicResponseHandler().handleResponse( response ).trim();
    assertThat( result, is( "FOO" ) );
}
 
Example #16
Source File: CXFOAuth2HttpClientFactory.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
  client.addRequestInterceptor(new HttpRequestInterceptor() {

    @Override
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
      request.removeHeaders(HttpHeaders.AUTHORIZATION);
      request.addHeader(HttpHeaders.AUTHORIZATION, OAuthClientUtils.createAuthorizationHeader(accessToken));
    }
  });
}
 
Example #17
Source File: AzureADOAuth2HttpClientFactory.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
  client.addRequestInterceptor(new HttpRequestInterceptor() {

    @Override
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
      request.removeHeaders(HttpHeaders.AUTHORIZATION);
      request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token.get("access_token").asText());
    }
  });
}
 
Example #18
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 #19
Source File: HTTPSession.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void resetInterceptors() {
  if (!TESTING)
    throw new UnsupportedOperationException();
  for (HttpRequestInterceptor hri : reqintercepts) {
    if (hri instanceof HTTPUtil.InterceptCommon)
      ((HTTPUtil.InterceptCommon) hri).clear();
  }
}
 
Example #20
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 #21
Source File: ConsulConfigBootstrapConfiguration.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public ConsulClient consulClient(ConsulProperties consulProperties,
                                 ConsulConfigProperties consulConfigProperties) {
    final int agentPort = consulProperties.getPort();
    final String agentHost = !StringUtils.isEmpty(consulProperties.getScheme())
            ? consulProperties.getScheme() + "://" + consulProperties.getHost()
            : consulProperties.getHost();

    logger.info("Init consul host: " + agentHost + " port: " + agentPort);
    if (consulProperties.getTls() != null) {
        ConsulProperties.TLSConfig tls = consulProperties.getTls();
        TLSConfig tlsConfig = new TLSConfig(
                tls.getKeyStoreInstanceType(),
                tls.getCertificatePath(),
                tls.getCertificatePassword(),
                tls.getKeyStorePath(),
                tls.getKeyStorePassword()
        );
        return new ConsulClient(agentHost, agentPort, tlsConfig);
    }
    HttpRequestInterceptor httpRequestInterceptor = new BmsCommonInterceptor();
    BmsHttpTransport httpTransport = new BmsHttpTransport(httpRequestInterceptor);
    ConsulRawClient rawClient = new ConsulRawClient(httpTransport.getHttpClient(),
            agentHost, agentPort, consulConfigProperties.getPath());
    return new ConsulClient(rawClient);
}
 
Example #22
Source File: StoregateSession.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoregateApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            request.addHeader(HttpHeaders.AUTHORIZATION,
                String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
        }
    }).build(),
        host).withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() :
        Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(
            host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl())
    );
    // Force login even if browser session already exists
    authorizationService.withParameter("prompt", "login");
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    configuration.addInterceptorLast(authorizationService);
    final CloseableHttpClient apache = configuration.build();
    final StoregateApiClient client = new StoregateApiClient(apache);
    final int timeout = PreferencesFactory.get().getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(),
        null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig()
        .register(new InputStreamProvider())
        .register(MultiPartFeature.class)
        .register(new JSON())
        .register(JacksonFeature.class)
        .connectorProvider(new HttpComponentsProvider(apache))));
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
 
Example #23
Source File: HttpClientGenerator.java    From blog-hunter with MIT License 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 #24
Source File: SofaTracerHttpClientBuilder.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
public static HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpAsyncClientBuilder,
                                                        String currentApp, String targetApp) {
    SofaTracerAsyncHttpInterceptor interceptor = new SofaTracerAsyncHttpInterceptor(
        getHttpClientTracer(), currentApp, targetApp);
    return httpAsyncClientBuilder.addInterceptorFirst((HttpRequestInterceptor) interceptor)
        .addInterceptorFirst((HttpResponseInterceptor) interceptor);
}
 
Example #25
Source File: HttpClientConfigTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testGetAndSetLastRequestInterceptor()
{
    HttpRequestInterceptor interceptor = mock(HttpRequestInterceptor.class);
    config.setLastRequestInterceptor(interceptor);
    assertEquals(interceptor, config.getLastRequestInterceptor());
}
 
Example #26
Source File: Sample.java    From aws-request-signing-apache-interceptor with Apache License 2.0 5 votes vote down vote up
CloseableHttpClient signingClientForServiceName(String serviceName) {
    AWS4Signer signer = new AWS4Signer();
    signer.setServiceName(serviceName);
    signer.setRegionName(AWS_REGION);

    HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(serviceName, signer, credentialsProvider);
    return HttpClients.custom()
            .addInterceptorLast(interceptor)
            .build();
}
 
Example #27
Source File: AwsRestHighLevelClient.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Injects the client builder with AWS credentials.
 * @param credentialsProvider is the AWS credentials provider.
 * @return self.
 */
public Builder withCredentials(AWSCredentialsProvider credentialsProvider)
{
    /**
     * endpoint:
     * https://search-movies-ne3fcqzfipy6jcrew2wca6kyqu.us-east-1.es.amazonaws.com
     *
     * domainSplits:
     * [0] = "https://search-movies-ne3fcqzfipy6jcrew2wca6kyqu"
     * [1] = "us-east-1"
     * [2] = "es"
     * [3] = "amazonaws"
     * [4] = "com"
     */
    List<String> domainSplits = domainSplitter.splitToList(endpoint);

    if (domainSplits.size() > 1) {
        signer.setRegionName(domainSplits.get(1));
        signer.setServiceName("es");
    }

    HttpRequestInterceptor interceptor =
            new AWSRequestSigningApacheInterceptor(signer.getServiceName(), signer, credentialsProvider);

    clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
            .addInterceptorLast(interceptor));

    return this;
}
 
Example #28
Source File: HttpClientConfig.java    From vividus with Apache License 2.0 4 votes vote down vote up
public void setLastRequestInterceptor(HttpRequestInterceptor lastRequestInterceptor)
{
    this.lastRequestInterceptor = lastRequestInterceptor;
}
 
Example #29
Source File: Twitter.java    From streams with Apache License 2.0 4 votes vote down vote up
private Twitter(TwitterConfiguration configuration) throws InstantiationException {
  this.configuration = configuration;
  this.rootUrl = TwitterProviderUtil.baseUrl(configuration);
  this.oauthInterceptor = new TwitterOAuthRequestInterceptor(configuration.getOauth());
  this.httpclient = HttpClientBuilder.create()
    .setDefaultRequestConfig(
      RequestConfig.custom()
        .setConnectionRequestTimeout(5000)
        .setConnectTimeout(5000)
        .setSocketTimeout(5000)
        .setCookieSpec("easy")
        .build()
    )
    .setMaxConnPerRoute(20)
    .setMaxConnTotal(100)
    .addInterceptorFirst(oauthInterceptor)
    .addInterceptorLast((HttpRequestInterceptor) (httpRequest, httpContext) -> LOGGER.debug(httpRequest.getRequestLine().getUri()))
    .addInterceptorLast((HttpResponseInterceptor) (httpResponse, httpContext) -> LOGGER.debug(httpResponse.getStatusLine().toString()))
    .build();
  this.restClientBuilder = RestClient.create()
    .httpClient(httpclient, true)
    .parser(
      JsonParser.DEFAULT.builder()
        .ignoreUnknownBeanProperties(true)
        .pojoSwaps(TwitterJodaDateSwap.class)
        .build())
    .serializer(
      JsonSerializer.DEFAULT.builder()
        .pojoSwaps(TwitterJodaDateSwap.class)
        .trimEmptyCollections(true)
        .trimEmptyMaps(true)
        .build())
    .rootUrl(rootUrl)
    .retryable(
      configuration.getRetryMax().intValue(),
      configuration.getRetrySleepMs().intValue(),
      new TwitterRetryHandler());
  if( configuration.getDebug() ) {
    restClientBuilder = restClientBuilder.debug();
  }

  this.restClient = restClientBuilder.build();
  this.mapper = StreamsJacksonMapper.getInstance();
}
 
Example #30
Source File: HttpClientConfig.java    From vividus with Apache License 2.0 4 votes vote down vote up
public HttpRequestInterceptor getLastRequestInterceptor()
{
    return lastRequestInterceptor;
}