Java Code Examples for org.apache.http.client.protocol.HttpClientContext#setRequestConfig()

The following examples show how to use org.apache.http.client.protocol.HttpClientContext#setRequestConfig() . 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: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private void addProxy( HttpClientContext context ) {
  String proxyHost = environmentSubstitute( this.proxyHostname );
  String proxyPort = environmentSubstitute( this.proxyPort );
  String nonProxyHosts = environmentSubstitute( this.nonProxyHosts );

  String hostName = environmentSubstitute( this.hostname );
  if ( Utils.isEmpty( proxyHost ) || Utils.isEmpty( proxyPort ) ) {
    return;
  }
  // skip applying proxy if non-proxy host matches
  if ( !Utils.isEmpty( nonProxyHosts ) && hostName.matches( nonProxyHosts ) ) {
    return;
  }
  HttpHost httpHost = new HttpHost( proxyHost, Integer.valueOf( proxyPort ) );

  RequestConfig requestConfig = RequestConfig.custom()
    .setProxy( httpHost )
    .build();

  context.setRequestConfig( requestConfig );
}
 
Example 2
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new HttpClientContext used for request execution.
 */
public static HttpClientContext newClientContext(HttpClientSettings settings,
                                                 Map<String, ? extends Object>
                                                         attributes) {
    final HttpClientContext clientContext = new HttpClientContext();

    if (attributes != null && !attributes.isEmpty()) {
        for (Map.Entry<String, ?> entry : attributes.entrySet()) {
            clientContext.setAttribute(entry.getKey(), entry.getValue());
        }
    }

    addPreemptiveAuthenticationProxy(clientContext, settings);

    RequestConfig.Builder builder = RequestConfig.custom();
    disableNormalizeUri(builder);

    clientContext.setRequestConfig(builder.build());
    clientContext.setAttribute(HttpContextUtils.DISABLE_SOCKET_PROXY_PROPERTY, settings.disableSocketProxy());
    return clientContext;

}
 
Example 3
Source File: MavenITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected Maven2Client createMaven2Client(final URL repositoryUrl, final String username, final String password)
    throws Exception
{
  AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setExpectContinueEnabled(true);
  HttpClientContext httpClientContext = HttpClientContext.create();
  httpClientContext.setRequestConfig(requestConfigBuilder.build());
  return new Maven2Client(
      HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
      httpClientContext,
      repositoryUrl.toURI()
  );
}
 
Example 4
Source File: HttpHelper.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public static byte[] getBytes(String url, int timeout) throws Exception {
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    CloseableHttpClient httpclient = builder.build();
    URI uri = new URIBuilder(url).build();
    RequestConfig config = custom().setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setSocketTimeout(timeout)
        .build();
    HttpGet httpGet = new HttpGet(uri);
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(config);
    CloseableHttpResponse response = httpclient.execute(httpGet, context);
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        long end = System.currentTimeMillis();
        long cost = end - start;
        if (logger.isWarnEnabled()) {
            logger.warn("post " + url + ", cost : " + cost);
        }
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode
                                       + ", error msg=" + errorMsg);
        }
    } finally {
        response.close();
        httpGet.releaseConnection();
    }
}
 
Example 5
Source File: ApacheHttpAsyncClientInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void performGet(String path) throws Exception {
    final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();

    RequestConfig requestConfig = RequestConfig.custom()
        .setCircularRedirectsAllowed(true)
        .build();
    HttpClientContext httpClientContext = HttpClientContext.create();
    httpClientContext.setRequestConfig(requestConfig);
    client.execute(new HttpGet(path), httpClientContext, new FutureCallback<>() {
        @Override
        public void completed(HttpResponse result) {
            responseFuture.complete(result);
        }

        @Override
        public void failed(Exception ex) {
            responseFuture.completeExceptionally(ex);
        }

        @Override
        public void cancelled() {
            responseFuture.cancel(true);
        }
    });

    responseFuture.get();
}
 
Example 6
Source File: ApacheUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new HttpClientContext used for request execution.
 */
public static HttpClientContext newClientContext(ProxyConfiguration proxyConfiguration) {
    HttpClientContext clientContext = new HttpClientContext();
    addPreemptiveAuthenticationProxy(clientContext, proxyConfiguration);

    RequestConfig.Builder builder = RequestConfig.custom();
    disableNormalizeUri(builder);

    clientContext.setRequestConfig(builder.build());
    return clientContext;

}
 
Example 7
Source File: NexusClientFactory.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
public T createClient(final URL repositoryUrl,
                      final String username,
                      final String password)
{
  checkNotNull(repositoryUrl);
  checkNotNull(username);
  checkNotNull(password);

  AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setExpectContinueEnabled(true);

  AuthCache authCache = new BasicAuthCache();
  authCache.put(new HttpHost(repositoryUrl.getHost(), repositoryUrl.getPort()), new BasicScheme());

  HttpClientContext httpClientContext = HttpClientContext.create();
  httpClientContext.setAuthCache(authCache);
  httpClientContext.setRequestConfig(requestConfigBuilder.build());

  try {
    return createClient(
        HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
        httpClientContext,
        repositoryUrl.toURI()
    );
  }
  catch (URISyntaxException e) {
    log.warn("Uri exception creating Client", e);
  }

  return null;
}
 
Example 8
Source File: BceHttpClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates HttpClient Context object based on the internal request.
 *
 * @param request The internal request.
 * @return HttpClient Context object.
 */
protected HttpClientContext createHttpContext(InternalRequest request) {
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled())
            .setSocketTimeout(this.config.getSocketTimeoutInMillis()).build());
    if (this.credentialsProvider != null) {
        context.setCredentialsProvider(this.credentialsProvider);
    }
    if (this.config.isProxyPreemptiveAuthenticationEnabled()) {
        AuthCache authCache = new BasicAuthCache();
        authCache.put(this.proxyHttpHost, new BasicScheme());
        context.setAuthCache(authCache);
    }
    return context;
}
 
Example 9
Source File: HttpHelper.java    From canal with Apache License 2.0 5 votes vote down vote up
public static byte[] getBytes(String url, int timeout) throws Exception {
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    CloseableHttpClient httpclient = builder.build();
    URI uri = new URIBuilder(url).build();
    RequestConfig config = custom().setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setSocketTimeout(timeout)
        .build();
    HttpGet httpGet = new HttpGet(uri);
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(config);
    CloseableHttpResponse response = httpclient.execute(httpGet, context);
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        long end = System.currentTimeMillis();
        long cost = end - start;
        if (logger.isWarnEnabled()) {
            logger.warn("post " + url + ", cost : " + cost);
        }
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode
                                       + ", error msg=" + errorMsg);
        }
    } finally {
        response.close();
        httpGet.releaseConnection();
    }
}
 
Example 10
Source File: SlaveServer.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void addProxy( HttpClientContext context ) {
  String proxyHost;
  String proxyPort;
  String nonProxyHosts;

  String hostName;

  lock.readLock().lock();
  try {
    proxyHost = environmentSubstitute( this.proxyHostname );
    proxyPort = environmentSubstitute( this.proxyPort );
    nonProxyHosts = environmentSubstitute( this.nonProxyHosts );

    hostName = environmentSubstitute( this.hostname );
  } finally {
    lock.readLock().unlock();
  }
  if ( Utils.isEmpty( proxyHost ) || Utils.isEmpty( proxyPort ) ) {
    return;
  }
  // skip applying proxy if non-proxy host matches
  if ( !Utils.isEmpty( nonProxyHosts ) && hostName.matches( nonProxyHosts ) ) {
    return;
  }
  HttpHost httpHost = new HttpHost( proxyHost, Integer.valueOf( proxyPort ) );

  RequestConfig requestConfig = RequestConfig.custom()
    .setProxy( httpHost )
    .build();

  context.setRequestConfig( requestConfig );
}