Java Code Examples for org.springframework.http.client.HttpComponentsClientHttpRequestFactory#setConnectTimeout()

The following examples show how to use org.springframework.http.client.HttpComponentsClientHttpRequestFactory#setConnectTimeout() . 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: RestTemplateConfig.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * httpRequestFactory.
 * 
 * @return
 */
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {

    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(
            30, TimeUnit.SECONDS);
    // max connection
    pollingConnectionManager.setMaxTotal(constants.getRestTemplateMaxTotal());

    pollingConnectionManager.setDefaultMaxPerRoute(constants.getRestTemplateMaxPerRoute());
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // add Keep-Alive
    httpClientBuilder
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
            new HttpComponentsClientHttpRequestFactory(httpClient);
    clientHttpRequestFactory.setReadTimeout(constants.getHttp_read_timeOut());
    clientHttpRequestFactory.setConnectTimeout(constants.getHttp_connect_timeOut());
    return clientHttpRequestFactory;
}
 
Example 2
Source File: DefaultAppValidationServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private static boolean dockerCheck() {
	boolean result = true;
	try {
		CloseableHttpClient httpClient
				= HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		requestFactory.setConnectTimeout(10000);
		requestFactory.setReadTimeout(10000);

		RestTemplate restTemplate = new RestTemplate(requestFactory);
		System.out.println("Testing access to " + DockerValidatorProperties.DOCKER_REGISTRY_URL
				+ "springcloudstream/log-sink-rabbit/tags");
		restTemplate.getForObject(DockerValidatorProperties.DOCKER_REGISTRY_URL
				+ "/springcloudstream/log-sink-rabbit/tags", String.class);
	}
	catch(Exception ex) {
		System.out.println("dockerCheck() failed. " + ex.getMessage());
		result = false;
	}
	return result;
}
 
Example 3
Source File: PromqlTest.java    From promql_java_client with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
	HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
	httpRequestFactory.setConnectTimeout(1000);
	httpRequestFactory.setReadTimeout(2000);
	HttpClient httpClient = HttpClientBuilder.create()
	 .setMaxConnTotal(100)
	 .setMaxConnPerRoute(10)
	 .build();
	httpRequestFactory.setHttpClient(httpClient);
	
	template = new RestTemplate(httpRequestFactory);
}
 
Example 4
Source File: HttpClientProvider.java    From staffjoy with MIT License 5 votes vote down vote up
protected RestTemplate createRestTemplate(MappingProperties mapping) {
    CloseableHttpClient client = createHttpClient(mapping).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
    requestFactory.setConnectTimeout(mapping.getTimeout().getConnect());
    requestFactory.setReadTimeout(mapping.getTimeout().getRead());
    return new RestTemplate(requestFactory);
}
 
Example 5
Source File: PdfServerClientConfig.java    From vics with MIT License 5 votes vote down vote up
@Bean
public RestTemplate pdfServerClient() {
    HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    httpRequestFactory.setConnectionRequestTimeout(CONNECT_TIMEOUT);
    httpRequestFactory.setReadTimeout(READ_TIMEOUT);
    httpRequestFactory.setConnectTimeout(CONNECT_TIMEOUT);

    return new RestTemplate(httpRequestFactory);
}
 
Example 6
Source File: HelloController.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private ClientHttpRequestFactory getClientHttpRequestFactory() {
  int timeout = 5000;
  HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
      new HttpComponentsClientHttpRequestFactory();
  clientHttpRequestFactory.setConnectTimeout(timeout);
  return clientHttpRequestFactory;
}
 
Example 7
Source File: SimpleRestTemplateBuilder.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public RestTemplate build(int readTimeout){
	
	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();  
       factory.setReadTimeout(readTimeout);//ms  
       factory.setConnectTimeout(3000);//ms 
       
       RestTemplate restTemplate = new RestTemplate(factory);
       List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
       interceptors.add(new RestTemplateAutoHeaderInterceptor());
       interceptors.add(new LoggingRequestInterceptor());
       restTemplate.setInterceptors(interceptors);
       //
       restTemplate.setErrorHandler(new CustomResponseErrorHandler());
	return restTemplate;
}
 
Example 8
Source File: RestTemplateFactory.java    From apollo with Apache License 2.0 5 votes vote down vote up
public void afterPropertiesSet() throws UnsupportedEncodingException {
  CloseableHttpClient httpClient = HttpClientBuilder.create().build();

  restTemplate = new RestTemplate(httpMessageConverters.getConverters());
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(httpClient);
  requestFactory.setConnectTimeout(portalConfig.connectTimeout());
  requestFactory.setReadTimeout(portalConfig.readTimeout());

  restTemplate.setRequestFactory(requestFactory);
}
 
Example 9
Source File: RESTFacade.java    From zstack with Apache License 2.0 5 votes vote down vote up
static TimeoutRestTemplate createRestTemplate(int readTimeout, int connectTimeout) {
    HttpComponentsClientHttpRequestFactory factory = new TimeoutHttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(readTimeout);
    factory.setConnectTimeout(connectTimeout);

    SSLContext sslContext = DefaultSSLVerifier.getSSLContext(DefaultSSLVerifier.trustAllCerts);

    if (sslContext != null) {
        factory.setHttpClient(HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(sslContext)
                .build());
    }

    TimeoutRestTemplate template = new TimeoutRestTemplate(factory);

    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
    stringHttpMessageConverter.setWriteAcceptCharset(true);
    for (int i = 0; i < template.getMessageConverters().size(); i++) {
        if (template.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
            template.getMessageConverters().remove(i);
            template.getMessageConverters().add(i, stringHttpMessageConverter);
            break;
        }
    }

    return template;
}
 
Example 10
Source File: RestTemplateFakeReactiveFeign.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <T> ReactiveFeign.Builder<T> builder(ReactiveOptions options) {
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(
          HttpClientBuilder.create().build());
  if (options.getConnectTimeoutMillis() != null) {
    requestFactory.setConnectTimeout(options.getConnectTimeoutMillis());
  }
  if (options.getReadTimeoutMillis() != null) {
    requestFactory.setReadTimeout(options.getReadTimeoutMillis());
  }
  return builder(new RestTemplate(requestFactory),
      options.isTryUseCompression() != null && options.isTryUseCompression());
}
 
Example 11
Source File: BaseApplicationStarter.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Bean
RestTemplate restTemplateNoneLB() {
	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	factory.setConnectTimeout(3000);
	factory.setReadTimeout(30000);
	return new RestTemplate(factory);
}
 
Example 12
Source File: TeamUpAutoConfiguration.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
@Bean(name = EVENT_REST_OPERATIONS)
public RestOperations eventRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(30000);
    factory.setReadTimeout(30000);
    return getRestOperations(factory);
}
 
Example 13
Source File: TeamUpAutoConfiguration.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
@Bean(name = FILE_REST_OPERATIONS)
public RestOperations fileRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(20000);
    factory.setReadTimeout(20000);
    RestTemplate restTemplate = (RestTemplate) RestTemplateFactory.getRestOperations(factory);
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    return restTemplate;
}
 
Example 14
Source File: ChatbotAutoConfiguration.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
@Bean
@Primary
public RestOperations messageRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(1000);
    factory.setReadTimeout(1000);
    return getRestOperations(factory);
}
 
Example 15
Source File: BackupStorageBase.java    From zstack with Apache License 2.0 5 votes vote down vote up
protected void exceptionIfImageSizeGreaterThanAvailableCapacity(String url) {
    if (CoreGlobalProperty.UNIT_TEST_ON) {
        return;
    }

    url = url.trim();
    if (!url.startsWith("http") && !url.startsWith("https")) {
        return;
    }

    HttpHeaders header;
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(CoreGlobalProperty.REST_FACADE_READ_TIMEOUT);
    factory.setConnectTimeout(CoreGlobalProperty.REST_FACADE_CONNECT_TIMEOUT);
    factory.setHttpClient(HttpClients.createDefault());
    RestTemplate template = new RestTemplate(factory);
    try {
        header = template.headForHeaders(URI.create(url));
        logger.debug(String.format("get header from %s: %s", url, header));
    } catch (Exception e) {
        throw new OperationFailureException(operr("failed to get header of image url %s: %s", url, e.toString()));
    }

    if (header == null) {
        throw new OperationFailureException(operr("failed to get header of image url %s", url));
    }

    long size = header.getContentLength();
    if (size == -1) {
        logger.error(String.format("failed to get image size from url %s, but ignore this error and proceed", url));
    } else if (size < ImageConstant.MINI_IMAGE_SIZE_IN_BYTE) {
        throw new OperationFailureException(operr("the image size get from url %s is %d bytes, " +
                "it's too small for an image, please check the url again.", url, size));
    } else if (size > self.getAvailableCapacity()) {
        throw new OperationFailureException(operr("the backup storage[uuid:%s, name:%s] has not enough capacity to download the image[%s]." +
                        "Required size:%s, available size:%s", self.getUuid(), self.getName(), url, size, self.getAvailableCapacity()));
    }
}
 
Example 16
Source File: ClientConfig.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Bean
KioOperations kioOperations() {
    final StupsOAuth2RestTemplate restTemplate = new StupsOAuth2RestTemplate(new StupsTokensAccessTokenProvider("kio", accessTokens));
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setConnectTimeout(4 * 1000);
    requestFactory.setReadTimeout(4 * 1000);
    restTemplate.setRequestFactory(requestFactory);
    restTemplate.setErrorHandler(new KioClientResponseErrorHandler());
    return new RestTemplateKioOperations(
            restTemplate,
            kioBaseUrl);
}
 
Example 17
Source File: HelperImpl.java    From heimdall with Apache License 2.0 4 votes vote down vote up
private HttpComponentsClientHttpRequestFactory httpClientRequestFactory() {
	HttpComponentsClientHttpRequestFactory httpClient = new HttpComponentsClientHttpRequestFactory();
	httpClient.setConnectTimeout(zuulProperty.getHost().getConnectTimeoutMillis());
	httpClient.setReadTimeout(zuulProperty.getHost().getSocketTimeoutMillis());
	return httpClient;
}
 
Example 18
Source File: ReCaptchaValidator.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public boolean validateCaptcha(HttpServletRequest request) throws ReCaptchaInvalidException, ReCaptchaScoreNonValidoException, ReCaptchaUnavailableException, ReCaptchaParametroResponseInvalidException {
	String reCaptchaResponse = getCaptchaResponse(request);
	if (!responseSanityCheck(reCaptchaResponse)) {
           throw new ReCaptchaParametroResponseInvalidException("Il parametro '"+this.captchaSettings.getGoogleCatpcha().getResponseParameter()+"' e' vuoto o contiene caratteri non validi.");
       }
	
	// "https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s"
	
	String payload = String.format(CaptchaCostanti.PAYLOAD_TEMPLATE, this.captchaSettings.getGoogleCatpcha().getSecretKey(), reCaptchaResponse, getClientIP(request));
	
	StringBuilder sbUrl = new StringBuilder();
	sbUrl.append(this.captchaSettings.getGoogleCatpcha().getServerURL());
	if(this.captchaSettings.getGoogleCatpcha().getServerURL().contains("?")) {
		sbUrl.append("&");
	} else{
		sbUrl.append("?");
	}
	sbUrl.append(payload);
	
	final URI verifyUri = URI.create(sbUrl.toString());
       try {
       	logger.debug("Richiesta validazione Captcha alla URL ["+verifyUri.toString()+"], Payload ["+payload+"]");
       	
       	// imposto i timeout di connessione
       	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
       	factory.setConnectTimeout(this.captchaSettings.getGoogleCatpcha().getConnectionTimeout());
       	factory.setReadTimeout(this.captchaSettings.getGoogleCatpcha().getReadTimeout());
       	
          	RestTemplate restTemplate = new RestTemplate(factory);
          	
          	final  CaptchaResponse googleResponse = restTemplate.getForObject(verifyUri, CaptchaResponse.class);
          	
           logger.debug("Verifica reCaptcha completata, ricevuto messaggio dal servizio di verifica: {} ", googleResponse.toString());

           if (!googleResponse.isSuccess()) {
               throw new ReCaptchaInvalidException("Verifica reCaptcha completata con insuccesso: Errori trovati ["+googleResponse.getErrorCodes()+"]");
           }
           else {
           	// controllo soglia score valido solo nella versione V3, nella V2 non e' presente nella risposta
           	if(googleResponse.getScore() != null) {
           		logger.debug("reCaptcha validato correttamente, controllo dello score: Ricevuto["+googleResponse.getScore()+"], Richiesto["+this.captchaSettings.getGoogleCatpcha().getSoglia()+"]");
           		if(googleResponse.getScore().doubleValue() < this.captchaSettings.getGoogleCatpcha().getSoglia()) {
           			throw new ReCaptchaScoreNonValidoException("Verifica reCaptcha completata con insuccesso: score non sufficiente");
           		}
           	}
           }
           
           return googleResponse.isSuccess();
       } catch (RestClientException rce) {
       	if(this.captchaSettings.getGoogleCatpcha().isDenyOnFail())        	
       		throw new ReCaptchaUnavailableException("Servizio non raggiungibile. Riprovare piu' tardi.", rce);
       	else {
       		logger.warn("Servizio verifica recaptcha non disponibile. Richiesta autorizzata per configurazione denyOnFail=false.");
       		return true;
       	}
       } 
}
 
Example 19
Source File: RestTemplateConfig.java    From LicenseDemo with Apache License 2.0 4 votes vote down vote up
/**
 * ClientHttpRequestFactory接口的另一种实现方式(推荐使用),即:
 * HttpComponentsClientHttpRequestFactory:底层使用Httpclient连接池的方式创建Http连接请求
 * @return HttpComponentsClientHttpRequestFactory
 */
@Bean
public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory(){
	//Httpclient连接池,长连接保持30秒
	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
	
	//设置总连接数
	connectionManager.setMaxTotal(1000);
	//设置同路由的并发数
	connectionManager.setDefaultMaxPerRoute(1000);
	
	//设置header
	List<Header> headers = new ArrayList<Header>();
	headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04"));
	headers.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
	headers.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"));
	headers.add(new BasicHeader("Connection", "keep-alive"));
	
	//创建HttpClient
       HttpClient httpClient = HttpClientBuilder.create()
               .setConnectionManager(connectionManager)
               .setDefaultHeaders(headers)
               .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) //设置重试次数
               .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) //设置保持长连接
               .build();
	
       //创建HttpComponentsClientHttpRequestFactory实例
       HttpComponentsClientHttpRequestFactory requestFactory = 
			new HttpComponentsClientHttpRequestFactory(httpClient);
	
       //设置客户端和服务端建立连接的超时时间
       requestFactory.setConnectTimeout(5000);
	//设置客户端从服务端读取数据的超时时间
       requestFactory.setReadTimeout(5000);
       //设置从连接池获取连接的超时时间,不宜过长
       requestFactory.setConnectionRequestTimeout(200);
       //缓冲请求数据,默认为true。通过POST或者PUT大量发送数据时,建议将此更改为false,以免耗尽内存
       requestFactory.setBufferRequestBody(false);
       
       return requestFactory;
}
 
Example 20
Source File: DockerCompose.java    From football-events with MIT License 4 votes vote down vote up
private RestTemplate restTemplate(long healthCheckTimeout) {
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(2000);
    clientHttpRequestFactory.setConnectionRequestTimeout(2000);
    return new RestTemplate(clientHttpRequestFactory);
}