org.apache.http.client.config.RequestConfig Java Examples

The following examples show how to use org.apache.http.client.config.RequestConfig. 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: ProxyClientHttpRequestFactory.java    From sinavi-jfw with Apache License 2.0 7 votes vote down vote up
/**
 * プロパティの設定が終了したあとにHttpClientのインスタンスを生成し、プロキシの設定を行います。
 * {@inheritDoc}
 */
@Override
public void afterPropertiesSet() throws Exception {

    Assert.notNull(proxyHost, "プロキシホスト(proxyHost)は必須です。");
    Assert.notNull(proxyPort, "プロキシポート番号(proxyPort)は必須です。");

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    HttpClientBuilder builder = HttpClients.custom();
    builder.setConnectionManager(connectionManager);
    if (authentication) {
        Assert.notNull(username, "ユーザ認証がtrueに設定された場合、ユーザ名(username)は必須です。");
        Assert.notNull(password, "ユーザ認証がtrueに設定された場合、パスワード(password)は必須です。");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(new HttpHost(proxyHost, Integer.parseInt(proxyPort)));
        builder.setRoutePlanner(routePlanner);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)), new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build());
    CloseableHttpClient client = builder.build();
    setHttpClient(client);
}
 
Example #2
Source File: HttpsAdminServerTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    this.httpAdminServer = new MobileAndHttpsServer(holder).start();

    httpsAdminServerUrl = String.format("https://localhost:%s/admin", properties.getHttpsPort());
    httpServerUrl = String.format("http://localhost:%s/", properties.getHttpPort());

    SSLContext sslcontext = TestUtil.initUnsecuredSSLContext();

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new MyHostVerifier());
    this.httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
            .build();

    httpServer = new HardwareAndHttpAPIServer(holder).start();

    String name = "[email protected]";
    String pass = "admin";
    admin = new User(name, SHA256Util.makeHash(pass, name), AppNameUtil.BLYNK, "local", "127.0.0.1", false, true);
    holder.userDao.add(admin);

    clientPair = initAppAndHardPair(properties);
}
 
Example #3
Source File: ExternalItemRecommendationAlgorithm.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Autowired
public ExternalItemRecommendationAlgorithm(ItemService itemService){
    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);
    cm.setDefaultMaxPerRoute(20);
    
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(DEFAULT_REQ_TIMEOUT)
            .setConnectTimeout(DEFAULT_CON_TIMEOUT)
            .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();
    
    httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .setDefaultRequestConfig(requestConfig)
            .build();
    
    this.itemService = itemService;
}
 
Example #4
Source File: UniverseClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public UniverseClient(String user, String password, String apiUrl, String authType,
                      int queryTimeout) {
  RequestConfig requestConfig = RequestConfig.custom()
      .setConnectTimeout(queryTimeout)
      .setSocketTimeout(queryTimeout)
      .build();
  PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
  cm.setMaxTotal(100);
  cm.setDefaultMaxPerRoute(100);
  cm.closeIdleConnections(10, TimeUnit.MINUTES);
  httpClient = HttpClientBuilder.create()
      .setConnectionManager(cm)
      .setDefaultRequestConfig(requestConfig)
      .build();

  this.user = user;
  this.password = password;
  this.authType = authType;
  if (StringUtils.isNotBlank(apiUrl)) {
    this.apiUrl = apiUrl.replaceAll("/$", "");
  }
}
 
Example #5
Source File: GovernanceApplication.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Scope("prototype")
@Bean("httpClient")
public CloseableHttpClient getHttpClient(GovernanceConfig config) {
    /**
     * config connect parameter
     */
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(config.getConnectionRequestTimeout())
            .setConnectTimeout(config.getHttpConnectTimeOut()).setSocketTimeout(config.getSocketTimeout()).build();

    cm.setMaxTotal(config.getMaxTotal());
    cm.setDefaultMaxPerRoute(config.getMaxPerRoute());
    return HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build();
}
 
Example #6
Source File: CloudFlareResolverCheck.java    From entrada with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected List<String> fetch() {

  int timeoutInMillis = timeout * 1000;
  RequestConfig config = RequestConfig
      .custom()
      .setConnectTimeout(timeoutInMillis)
      .setConnectionRequestTimeout(timeoutInMillis)
      .setSocketTimeout(timeoutInMillis)
      .build();
  CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

  List<String> subnets = new ArrayList<>();
  process(client, urlV4, subnets);
  process(client, urlV6, subnets);

  return subnets;
}
 
Example #7
Source File: RestFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the RequestConfig object by setting HttpClient settings defined in the rest config.
 * @param restConfig
 * @param proxy
 * @return
 */
protected static RequestConfig getRequestConfig(RestConfig restConfig, Optional<HttpHost> proxy) {
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  if (restConfig.getConnectTimeout() != null) {
    requestConfigBuilder.setConnectTimeout(restConfig.getConnectTimeout());
  }
  if (restConfig.getConnectionRequestTimeout() != null) {
    requestConfigBuilder.setConnectionRequestTimeout(restConfig.getConnectionRequestTimeout());
  }
  if (restConfig.getSocketTimeout() != null) {
    requestConfigBuilder.setSocketTimeout(restConfig.getSocketTimeout());
  }

  proxy.ifPresent(requestConfigBuilder::setProxy);
  return requestConfigBuilder.build();
}
 
Example #8
Source File: HttpComponentsClientHttpRequestFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge the given {@link HttpClient}-level {@link RequestConfig} with
 * the factory-level {@link RequestConfig}, if necessary.
 * @param clientConfig the config held by the current
 * @return the merged request config
 * @since 4.2
 */
protected RequestConfig mergeRequestConfig(RequestConfig clientConfig) {
	if (this.requestConfig == null) {  // nothing to merge
		return clientConfig;
	}

	RequestConfig.Builder builder = RequestConfig.copy(clientConfig);
	int connectTimeout = this.requestConfig.getConnectTimeout();
	if (connectTimeout >= 0) {
		builder.setConnectTimeout(connectTimeout);
	}
	int connectionRequestTimeout = this.requestConfig.getConnectionRequestTimeout();
	if (connectionRequestTimeout >= 0) {
		builder.setConnectionRequestTimeout(connectionRequestTimeout);
	}
	int socketTimeout = this.requestConfig.getSocketTimeout();
	if (socketTimeout >= 0) {
		builder.setSocketTimeout(socketTimeout);
	}
	return builder.build();
}
 
Example #9
Source File: HttpSmartyStreetsModule.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Provides @Singleton
public CloseableHttpClient provideCloseableHttpClient(SmartyStreetsClientConfig config)
{
   int timeoutMillis = (int) SECONDS.toMillis(config.getTimeoutSecs());

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

   CloseableHttpClient httpClient = HttpClientBuilder.create()
      .setDefaultRequestConfig(requestConfig)
      .build();

   // TODO: Customize the settings on the default PoolingHttpClientConnectionManager created by the
   // HttpClientBuilder.  Or we can build our own, but the default one has a lot of stuff set on it that we'd have to
   // do ourselves.
   //PoolingHttpClientConnectionManager connManager =
   //   (PoolingHttpClientConnectionManager) httpClient.getConnectionManager();
   //connManager.set...

   return httpClient;
}
 
Example #10
Source File: ProActiveVersionUtility.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static String getProActiveServerVersion(ApplicationContext currentContext) {
    int timeout = (int) TimeUnit.SECONDS.toMillis(2);

    RequestConfig config = RequestConfig.custom()
                                        .setConnectTimeout(timeout)
                                        .setConnectionRequestTimeout(timeout)
                                        .setSocketTimeout(timeout)
                                        .build();

    try (CloseableHttpClient httpClient = new HttpClientBuilder().setDefaultRequestConfig(config)
                                                                 .useSystemProperties()
                                                                 .build()) {

        HttpGet getMethod = new HttpGet(currentContext.getResourceUrl("version"));
        HttpResponse response = httpClient.execute(getMethod);

        String jsonObject = handleResponse(response);
        if (jsonObject != null)
            return jsonObject;
    } catch (IOException ignore) {
        // ignore exception, default value will be used
    }

    return VERSION_UNDEFINED;
}
 
Example #11
Source File: HttpClientPool.java    From FATE-Serving with Apache License 2.0 6 votes vote down vote up
public static void initPool() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
                Dict.HTTPS, sslsf).build();
        poolConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolConnManager.setMaxTotal(500);
        poolConnManager.setDefaultMaxPerRoute(200);
        int socketTimeout = 10000;
        int connectTimeout = 10000;
        int connectionRequestTimeout = 10000;
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                connectTimeout).build();
        httpClient = getConnection();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("init http client pool failed:", ex);
    }
}
 
Example #12
Source File: ExecutionNodeTaskDispatcherImpl.java    From flux with Apache License 2.0 6 votes vote down vote up
@Inject
public ExecutionNodeTaskDispatcherImpl(@Named("connector.max.connections") Integer maxConnections, @Named("connector.max.connections.per.route") Integer maxConnectionsPerRoute,
                                       @Named("connector.connection.timeout") Integer connectionTimeout, @Named("connector.socket.timeout") Integer socketTimeOut,
                                       MetricsClient metricsClient) {
    RequestConfig clientConfig = RequestConfig.custom()
            .setConnectTimeout((connectionTimeout).intValue())
            .setSocketTimeout((socketTimeOut).intValue())
            .setConnectionRequestTimeout((socketTimeOut).intValue())
            .build();
    PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
    syncConnectionManager.setMaxTotal(maxConnections);
    syncConnectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager)
            .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        HttpClientUtils.closeQuietly(closeableHttpClient);
    }));
    this.metricsClient = metricsClient;
}
 
Example #13
Source File: ElasticsearchClient.java    From elasticsearch-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static HttpClient buildHttpClient(HttpClientConnectionManager connectionManager)
{
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1500)
            .setConnectionRequestTimeout(1500)
            .build();

    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            // use the default retry handler:
            // https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e305
            .build();

    return httpClient;
}
 
Example #14
Source File: AbstractHttpClient.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the http client.
 *
 * @param builder client builder to configure
 */
protected void configureClient(HttpClientBuilder builder)
{
    if ( getRemoteHttpCacheAttributes().getMaxConnectionsPerHost() > 0 )
    {
        builder.setMaxConnTotal(getRemoteHttpCacheAttributes().getMaxConnectionsPerHost());
        builder.setMaxConnPerRoute(getRemoteHttpCacheAttributes().getMaxConnectionsPerHost());
    }

    builder.setDefaultRequestConfig(RequestConfig.custom()
            .setConnectTimeout(getRemoteHttpCacheAttributes().getConnectionTimeoutMillis())
            .setSocketTimeout(getRemoteHttpCacheAttributes().getSocketTimeoutMillis())
            // By default we instruct HttpClient to ignore cookies.
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .build());
}
 
Example #15
Source File: MCRURIResolver.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
MCRRESTResolver() {
    CacheConfig cacheConfig = CacheConfig.custom()
        .setMaxObjectSize(MAX_OBJECT_SIZE)
        .setMaxCacheEntries(MAX_CACHE_ENTRIES)
        .build();
    RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(REQUEST_TIMEOUT)
        .setSocketTimeout(REQUEST_TIMEOUT)
        .build();
    this.restClient = CachingHttpClients.custom()
        .setCacheConfig(cacheConfig)
        .setDefaultRequestConfig(requestConfig)
        .setUserAgent(MCRHttpUtils.getHttpUserAgent())
        .useSystemProperties()
        .build();
    MCRShutdownHandler.getInstance().addCloseable(this::close);
    this.logger = LogManager.getLogger();
}
 
Example #16
Source File: LoolFileConverter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static byte[] convert(String baseUrl, InputStream sourceInputStream) throws IOException {

        int timeoutMillis = 5000;
        RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(timeoutMillis)
            .setConnectionRequestTimeout(timeoutMillis)
            .setSocketTimeout(timeoutMillis * 1000).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpPost httpPost = new HttpPost(baseUrl + "/lool/convert-to/pdf");

        HttpEntity multipart = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("data", sourceInputStream, ContentType.MULTIPART_FORM_DATA, "anything")
            .build();

        httpPost.setEntity(multipart);
        CloseableHttpResponse response = client.execute(httpPost);
        byte[] convertedFileBytes = EntityUtils.toByteArray(response.getEntity());
        client.close();
        return convertedFileBytes;
    }
 
Example #17
Source File: MaterialVideoInfoRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
public WxMpMaterialVideoInfoResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  Map<String, String> params = new HashMap<>();
  params.put("media_id", materialId);
  httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
  CloseableHttpResponse response = httpclient.execute(httpPost);
  String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
  WxError error = WxError.fromJson(responseContent);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  } else {
    return WxMpMaterialVideoInfoResult.fromJson(responseContent);
  }
}
 
Example #18
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private RequestConfig mergeRequestConfig(RequestConfig defaultRequestConfig) {
	if (this.requestConfig == null) { // nothing to merge
		return defaultRequestConfig;
	}
	RequestConfig.Builder builder = RequestConfig.copy(defaultRequestConfig);
	int connectTimeout = this.requestConfig.getConnectTimeout();
	if (connectTimeout >= 0) {
		builder.setConnectTimeout(connectTimeout);
	}
	int connectionRequestTimeout = this.requestConfig.getConnectionRequestTimeout();
	if (connectionRequestTimeout >= 0) {
		builder.setConnectionRequestTimeout(connectionRequestTimeout);
	}
	int socketTimeout = this.requestConfig.getSocketTimeout();
	if (socketTimeout >= 0) {
		builder.setSocketTimeout(socketTimeout);
	}
	return builder.build();
}
 
Example #19
Source File: HttpComponentsHttpInvokerRequestExecutorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultSettingsOfHttpClientMergedOnExecutorCustomization() throws IOException {
	RequestConfig defaultConfig = RequestConfig.custom().setConnectTimeout(1234).build();
	CloseableHttpClient client = mock(CloseableHttpClient.class,
			withSettings().extraInterfaces(Configurable.class));
	Configurable configurable = (Configurable) client;
	given(configurable.getConfig()).willReturn(defaultConfig);

	HttpComponentsHttpInvokerRequestExecutor executor =
			new HttpComponentsHttpInvokerRequestExecutor(client);
	HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service");
	HttpPost httpPost = executor.createHttpPost(config);
	assertSame("Default client configuration is expected", defaultConfig, httpPost.getConfig());

	executor.setConnectionRequestTimeout(4567);
	HttpPost httpPost2 = executor.createHttpPost(config);
	assertNotNull(httpPost2.getConfig());
	assertEquals(4567, httpPost2.getConfig().getConnectionRequestTimeout());
	// Default connection timeout merged
	assertEquals(1234, httpPost2.getConfig().getConnectTimeout());
}
 
Example #20
Source File: HttpClientManager.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public CloseableHttpClient build() {
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.setConnectionManager( manager );

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  if ( socketTimeout > 0 ) {
    requestConfigBuilder.setSocketTimeout( socketTimeout );
  }
  if ( connectionTimeout > 0 ) {
    requestConfigBuilder.setConnectTimeout( socketTimeout );
  }
  if ( proxy != null ) {
    requestConfigBuilder.setProxy( proxy );
  }
  httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );

  if ( provider != null ) {
    httpClientBuilder.setDefaultCredentialsProvider( provider );
  }
  if ( redirectStrategy != null ) {
    httpClientBuilder.setRedirectStrategy( redirectStrategy );
  }

  return httpClientBuilder.build();
}
 
Example #21
Source File: LogSender.java    From desktop with GNU General Public License v3.0 6 votes vote down vote up
public boolean send(File compressedLog) throws IOException {
    
    boolean success = true;
    
    HttpClient client = HttpClientBuilder.create().build();
    HttpPut request = new HttpPut(serverURL+"?type=compress");
    request.addHeader("computer", config.getDeviceName());
    
    // Set request parameters
    RequestConfig.Builder reqConf = RequestConfig.custom();
    reqConf.setSocketTimeout(2000);
    reqConf.setConnectTimeout(1000);
    request.setConfig(reqConf.build());

    setRequest(request, compressedLog);

    HttpResponse response = client.execute(request);

    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode != 201) {
        success = false;
    }
    
    return success;
}
 
Example #22
Source File: SimplePostRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String postEntity) throws WxErrorException, ClientProtocolException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  }
}
 
Example #23
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private RequestConfig mergeRequestConfig(RequestConfig defaultRequestConfig) {
	if (this.requestConfig == null) {  // nothing to merge
		return defaultRequestConfig;
	}

	RequestConfig.Builder builder = RequestConfig.copy(defaultRequestConfig);
	int connectTimeout = this.requestConfig.getConnectTimeout();
	if (connectTimeout >= 0) {
		builder.setConnectTimeout(connectTimeout);
	}
	int connectionRequestTimeout = this.requestConfig.getConnectionRequestTimeout();
	if (connectionRequestTimeout >= 0) {
		builder.setConnectionRequestTimeout(connectionRequestTimeout);
	}
	int socketTimeout = this.requestConfig.getSocketTimeout();
	if (socketTimeout >= 0) {
		builder.setSocketTimeout(socketTimeout);
	}
	return builder.build();
}
 
Example #24
Source File: HttpComponentsClientHttpRequestFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Merge the given {@link HttpClient}-level {@link RequestConfig} with
 * the factory-level {@link RequestConfig}, if necessary.
 * @param clientConfig the config held by the current
 * @return the merged request config
 * @since 4.2
 */
protected RequestConfig mergeRequestConfig(RequestConfig clientConfig) {
	if (this.requestConfig == null) {  // nothing to merge
		return clientConfig;
	}

	RequestConfig.Builder builder = RequestConfig.copy(clientConfig);
	int connectTimeout = this.requestConfig.getConnectTimeout();
	if (connectTimeout >= 0) {
		builder.setConnectTimeout(connectTimeout);
	}
	int connectionRequestTimeout = this.requestConfig.getConnectionRequestTimeout();
	if (connectionRequestTimeout >= 0) {
		builder.setConnectionRequestTimeout(connectionRequestTimeout);
	}
	int socketTimeout = this.requestConfig.getSocketTimeout();
	if (socketTimeout >= 0) {
		builder.setSocketTimeout(socketTimeout);
	}
	return builder.build();
}
 
Example #25
Source File: HttpRequestExecutors.java    From caravan with Apache License 2.0 6 votes vote down vote up
public static String executeString(CloseableHttpClient client, String uri, String method, ListMultimap<String, String> headers, RequestConfig config,
        Object data, StreamSerializer serializer, boolean gzipped) {
    config = RequestConfigs.createCascadedRequestConfig(client, config);

    if (serializer != null) {
        if (headers == null)
            headers = ArrayListMultimap.create();
        if (!headers.containsKey(HttpHeaders.CONTENT_TYPE))
            headers.put(HttpHeaders.CONTENT_TYPE, serializer.contentType());
        if (!headers.containsKey(HttpHeaders.ACCEPT))
            headers.put(HttpHeaders.ACCEPT, serializer.contentType());
    }

    HttpUriRequest request = HttpRequestFactory.createRequest(uri, method, headers, config, data, serializer, gzipped);
    return executeString(client, request);
}
 
Example #26
Source File: HttpClientUtils.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
public static String getData(final HttpClient httpClient,
    final RequestConfig requestConfig,
    final String host,
    final int port,
    final String path) throws IOException, URISyntaxException {
  URI uri = new URIBuilder()
      .setScheme("http")
      .setHost(host)
      .setPort(port)
      .setPath(path)
      .build();

  HttpGet httpGet = new HttpGet(uri);
  httpGet.setConfig(requestConfig);

  return httpClient.execute(httpGet, HttpClientUtils.createResponseBodyExtractor(path));
}
 
Example #27
Source File: LongPollingChannelLifecycle.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Inject
public LongPollingChannelLifecycle(CloseableHttpClient httpclient,
                                   RequestConfig defaultRequestConfig,
                                   @Named(MessagingPropertyKeys.CHANNELID) String channelId,
                                   @Named(MessagingPropertyKeys.RECEIVERID) String receiverId,
                                   ObjectMapper objectMapper,
                                   HttpConstants httpConstants,
                                   HttpRequestFactory httpRequestFactory) {
    this.httpclient = httpclient;
    this.defaultRequestConfig = defaultRequestConfig;
    this.channelId = channelId;
    this.receiverId = receiverId;
    this.objectMapper = objectMapper;
    this.httpConstants = httpConstants;
    this.httpRequestFactory = httpRequestFactory;
}
 
Example #28
Source File: ApacheSyncClientExecutor.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public void initialize(ThunderProperties properties, boolean https) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
            .setConnectionRequestTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
            .setSocketTimeout(properties.getInteger(ThunderConstant.APACHE_SO_TIMEOUT_ATTRIBUTE_NAME))
            .build();

    HttpClientBuilder clientBuilder = HttpClients.custom();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    if (https) {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
    }

    httpSyncClient = clientBuilder.build();

    LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
 
Example #29
Source File: WxCpServiceApacheHttpClientImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  if (this.configStorage.isAccessTokenExpired() || forceRefresh) {
    synchronized (this.globalAccessTokenRefreshLock) {
      if (this.configStorage.isAccessTokenExpired()) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?"
          + "&corpid=" + this.configStorage.getCorpId()
          + "&corpsecret=" + this.configStorage.getCorpSecret();
        try {
          HttpGet httpGet = new HttpGet(url);
          if (this.httpProxy != null) {
            RequestConfig config = RequestConfig.custom()
              .setProxy(this.httpProxy).build();
            httpGet.setConfig(config);
          }
          String resultContent = null;
          try (CloseableHttpClient httpclient = getRequestHttpClient();
               CloseableHttpResponse response = httpclient.execute(httpGet)) {
            resultContent = new BasicResponseHandler().handleResponse(response);
          } finally {
            httpGet.releaseConnection();
          }
          WxError error = WxError.fromJson(resultContent, WxType.CP);
          if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
          }
          WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
          this.configStorage.updateAccessToken(
            accessToken.getAccessToken(), accessToken.getExpiresIn());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
  return this.configStorage.getAccessToken();
}
 
Example #30
Source File: FetchDataTest.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient getHttpClient(final HttpHost proxy, final boolean redirects, final CookieStore cookieStore) {
	final Builder builder = RequestConfig.custom()
			.setRedirectsEnabled(redirects)
			.setMaxRedirects(5);
	if (proxy != null) builder.setProxy(proxy);
	final RequestConfig requestConfig = builder.build();
	return HttpClients.custom()
			.setDefaultRequestConfig(requestConfig)
			.setDefaultCookieStore(cookieStore)
			.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
			.build();
}