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

The following examples show how to use org.apache.http.client.config.RequestConfig. These examples are extracted from open source projects. 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 Project: sinavi-jfw   Author: ctc-g   File: ProxyClientHttpRequestFactory.java    License: 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 Project: WeEvent   Author: WeBankFinTech   File: GovernanceApplication.java    License: 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 #3
Source Project: entrada   Author: SIDN   File: CloudFlareResolverCheck.java    License: 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 #4
Source Project: metron   Author: apache   File: RestFunctions.java    License: 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 #5
Source Project: elasticsearch-maven-plugin   Author: alexcojocaru   File: ElasticsearchClient.java    License: 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 #6
Source Project: joynr   Author: bmwcarit   File: LongPollingChannelLifecycle.java    License: 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 #7
Source Project: mycore   Author: MyCoRe-Org   File: MCRURIResolver.java    License: 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 #8
Source Project: sakai   Author: sakaiproject   File: LoolFileConverter.java    License: 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 #9
Source Project: spring4-understanding   Author: langtianya   File: HttpComponentsHttpInvokerRequestExecutor.java    License: 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 #10
Source Project: pentaho-kettle   Author: pentaho   File: HttpClientManager.java    License: 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 #11
Source Project: desktop   Author: stacksync   File: LogSender.java    License: 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 #12
Source Project: weixin-java-tools   Author: chanjarster   File: SimplePostRequestExecutor.java    License: 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 #13
Source Project: caravan   Author: ctripcorp   File: HttpRequestExecutors.java    License: 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 #14
Source Project: uReplicator   Author: uber   File: HttpClientUtils.java    License: 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 #15
Source Project: blynk-server   Author: blynkkk   File: HttpsAdminServerTest.java    License: 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 #16
Source Project: java-technology-stack   Author: codeEngraver   File: HttpComponentsClientHttpRequestFactory.java    License: 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 #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: HttpComponentsHttpInvokerRequestExecutor.java    License: 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 #18
Source Project: spring-analysis-note   Author: Vip-Augus   File: HttpComponentsHttpInvokerRequestExecutorTests.java    License: 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 #19
Source Project: weixin-java-tools   Author: chanjarster   File: MaterialVideoInfoRequestExecutor.java    License: 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 #20
Source Project: commons-jcs   Author: apache   File: AbstractHttpClient.java    License: 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 #21
Source Project: FATE-Serving   Author: FederatedAI   File: HttpClientPool.java    License: 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 #22
Source Project: arcusplatform   Author: arcus-smart-home   File: HttpSmartyStreetsModule.java    License: 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 #23
Source Project: lams   Author: lamsfoundation   File: HttpComponentsClientHttpRequestFactory.java    License: 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 #24
Source Project: flux   Author: flipkart-incubator   File: ExecutionNodeTaskDispatcherImpl.java    License: 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 #25
Source Project: seldon-server   Author: SeldonIO   File: ExternalItemRecommendationAlgorithm.java    License: 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 #26
Source Project: zeppelin   Author: apache   File: UniverseClient.java    License: 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 #27
Source Project: scheduling   Author: ow2-proactive   File: ProActiveVersionUtility.java    License: 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 #28
Source Project: newblog   Author: Zephery   File: LibraryUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void init() {
    context = HttpClientContext.create();
    cookieStore = new BasicCookieStore();
    // 配置超时时间(连接服务端超时1秒,请求数据返回超时2秒)
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
            .setConnectionRequestTimeout(60000).build();
    // 设置默认跳转以及存储cookie
    httpClient = HttpClientBuilder.create()
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore).build();
}
 
Example #29
Source Project: s2g-zuul   Author: spring2go   File: MobileExecuteRoute.java    License: MIT License 5 votes vote down vote up
private RequestConfig buildRequestConfig(String routName, String groupName) {

		RequestConfig.Builder builder = RequestConfig.custom();

		int connectTimeout = DynamicPropertyFactory.getInstance().getIntProperty(routName + ".connect.timeout", 0)
				.get();
		if (connectTimeout == 0) {
			connectTimeout = DynamicPropertyFactory.getInstance().getIntProperty(groupName + ".connect.timeout", 0)
					.get();
		}
		if (connectTimeout == 0) {
			connectTimeout = DynamicPropertyFactory.getInstance().getIntProperty("zuul.connect.timeout.global", 2000)
					.get();
		}
		builder.setConnectTimeout(connectTimeout);

		int socketTimeout = DynamicPropertyFactory.getInstance().getIntProperty(routName + ".socket.timeout", 0).get();
		if (socketTimeout == 0) {
			socketTimeout = DynamicPropertyFactory.getInstance().getIntProperty(groupName + ".socket.timeout", 0).get();
		}
		if (socketTimeout == 0) {
			socketTimeout = DynamicPropertyFactory.getInstance().getIntProperty("zuul.socket.timeout.global", 1000)
					.get();
		}
		builder.setSocketTimeout(socketTimeout);

		int requestConnectionTimeout = DynamicPropertyFactory.getInstance()
				.getIntProperty(routName + ".request.connection.timeout", 0).get();
		if (requestConnectionTimeout == 0) {
			requestConnectionTimeout = DynamicPropertyFactory.getInstance()
					.getIntProperty(groupName + ".request.connection.timeout", 0).get();
		}
		if (requestConnectionTimeout == 0) {
			requestConnectionTimeout = DynamicPropertyFactory.getInstance()
					.getIntProperty("zuul.request.connection.timeout.global", 10).get();
		}
		builder.setConnectionRequestTimeout(requestConnectionTimeout);

		return builder.build();
	}
 
Example #30
Source Project: cicada   Author: Yirendai   File: HttpPostDeliverService.java    License: MIT License 5 votes vote down vote up
public HttpPostDeliverService(final String postUrl, final int connectTimeout, final int soTimeout) {
  httpClient = HttpAsyncClients.createDefault();
  httpClient.start();

  httpPost = new HttpPost(postUrl);
  final RequestConfig requestConfig =
      RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(soTimeout).build();
  httpPost.setConfig(requestConfig);

  httpPost.setHeader("Content-type", "application/json");
  httpPost.setHeader("Content-Type", "text/html;charset=UTF-8");
}