org.springframework.http.client.ClientHttpRequestFactory Java Examples

The following examples show how to use org.springframework.http.client.ClientHttpRequestFactory. 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: WxApiHttpRequestFactory.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
/**
 * 获取连接工厂
 *
 * @return the result
 */
private ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpClient httpClient = getHttpClient();
    // httpClient连接配置,底层是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 连接超时
    clientHttpRequestFactory.setConnectTimeout(wxProperties.getInvoker().getConnectTimeout());
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(wxProperties.getInvoker().getReadTimeout());
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(wxProperties.getInvoker().getConnectionRequestTimeout());
    return clientHttpRequestFactory;
}
 
Example #2
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 #3
Source File: ExtRestTemplate.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public ExtRestTemplate(ClientHttpRequestFactory requestFactory){
		super();
		/*CUtils.findByClass(this.getMessageConverters(), MappingJackson2HttpMessageConverter.class)
				.ifPresent(p->{
					MappingJackson2HttpMessageConverter convertor = p.getValue();
					convertor.setObjectMapper(JsonMapper.IGNORE_NULL.getObjectMapper());
					convertor.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, 
																	MediaType.APPLICATION_JSON_UTF8,
																	MediaType.TEXT_PLAIN));
				});*/
		CUtils.replaceOrAdd(getMessageConverters(), MappingJackson2HttpMessageConverter.class, new ApiclientJackson2HttpMessageConverter());
		CUtils.replaceOrAdd(getMessageConverters(), MappingJackson2XmlHttpMessageConverter.class, new ApiclientJackson2XmlMessageConverter());
		
		applyDefaultCharset();
		
		if(requestFactory!=null){
			this.setRequestFactory(requestFactory);
//			this.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
		}
		this.setErrorHandler(new OnExtRestErrorHandler());
	}
 
Example #4
Source File: RestTemplateBuilder.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Create the {@link RestTemplate} to use.
 * @return the {@link RestTemplate} to use.
 */
protected RestTemplate createTemplate() {

	ClientHttpRequestFactory requestFactory = this.requestFactory.get();

	LinkedHashMap<String, String> defaultHeaders = new LinkedHashMap<>(this.defaultHeaders);
	LinkedHashSet<RestTemplateRequestCustomizer<ClientHttpRequest>> requestCustomizers = new LinkedHashSet<>(
			this.requestCustomizers);

	RestTemplate restTemplate = VaultClients.createRestTemplate(this.endpointProvider,
			new RestTemplateBuilderClientHttpRequestFactoryWrapper(requestFactory, requestCustomizers));

	restTemplate.getInterceptors().add((httpRequest, bytes, clientHttpRequestExecution) -> {

		HttpHeaders headers = httpRequest.getHeaders();
		defaultHeaders.forEach((key, value) -> {
			if (!headers.containsKey(key)) {
				headers.add(key, value);
			}
		});

		return clientHttpRequestExecution.execute(httpRequest, bytes);
	});

	return restTemplate;
}
 
Example #5
Source File: HashicorpKeyVaultServiceFactoryUtilTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void configureClientAuthenticationIfOnlyRoleIdAndSecretIdSetThenAppRoleMethod() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn("role-id");
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn("secret-id");
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn(null);

    when(keyVaultConfig.getProperty("approlePath")).thenReturn(Optional.of("somepath"));

    ClientAuthentication result = util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint);

    assertThat(result).isInstanceOf(AppRoleAuthentication.class);
}
 
Example #6
Source File: RestTemplateFactory.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public static RestOperations createCommonsHttpRestTemplate(int maxConnPerRoute, int maxConnTotal,
                                                           int connectTimeout, int soTimeout, int retryTimes, RetryPolicyFactory retryPolicyFactory) {
    HttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(maxConnPerRoute)
            .setMaxConnTotal(maxConnTotal)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build())
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).build())
            .build();
    ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    RestTemplate restTemplate = new RestTemplate(factory);
    //set jackson mapper
    for (HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
        if (hmc instanceof MappingJackson2HttpMessageConverter) {
            ObjectMapper objectMapper = createObjectMapper();
            MappingJackson2HttpMessageConverter mj2hmc = (MappingJackson2HttpMessageConverter) hmc;
            mj2hmc.setObjectMapper(objectMapper);
        }
    }

    return (RestOperations) Proxy.newProxyInstance(RestOperations.class.getClassLoader(),
            new Class[]{RestOperations.class},
            new RetryableRestOperationsHandler(restTemplate, retryTimes, retryPolicyFactory));
}
 
Example #7
Source File: HashicorpKeyVaultServiceFactoryUtilTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void configureClientAuthenticationIfNoEnvVarSetThenException() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn(null);

    Throwable ex = catchThrowable(() -> util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint));

    assertThat(ex).isExactlyInstanceOf(HashicorpCredentialNotSetException.class);
    assertThat(ex.getMessage()).isEqualTo("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method.  Alternatively set " + HASHICORP_TOKEN + " to authenticate using the Token method");
}
 
Example #8
Source File: CredHubTemplate.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link CredHubTemplate} using the provided connection properties,
 * {@link ClientHttpRequestFactory}, and OAuth2 support.
 * @param properties the CredHub connection properties; must not be {@literal null}
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 * @param clientRegistrationRepository a repository of OAuth2 client registrations
 * @param authorizedClientRepository a repository of authorized OAuth2 clients
 */
public CredHubTemplate(CredHubProperties properties, ClientHttpRequestFactory clientHttpRequestFactory,
		ClientRegistrationRepository clientRegistrationRepository,
		OAuth2AuthorizedClientRepository authorizedClientRepository) {
	Assert.notNull(properties, "properties must not be null");
	Assert.notNull(clientHttpRequestFactory, "clientHttpRequestFactory must not be null");
	Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository must not be null");

	this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties, clientHttpRequestFactory,
			clientRegistrationRepository, authorizedClientRepository);
	this.usingOAuth2 = true;
}
 
Example #9
Source File: ChangelogCreator.java    From salespoint with Apache License 2.0 5 votes vote down vote up
private static RestTemplate setUpRestTemplate() throws IOException {

		FileSystemResource resource = new FileSystemResource("env.properties");
		ResourcePropertySource propertySource = new ResourcePropertySource(resource);
		String username = propertySource.getProperty("github.username").toString();
		String password = propertySource.getProperty("github.password").toString();

		BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

		AuthCache authCache = new BasicAuthCache();
		authCache.put(new HttpHost("api.github.com", 443, "https"), new BasicScheme());

		final HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credentialsProvider);
		context.setAuthCache(authCache);

		ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build()) {

			@Override
			protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
				return context;
			}
		};

		RestTemplate template = new RestTemplate();
		template.setRequestFactory(factory);

		return template;
	}
 
Example #10
Source File: ClientCertificateAuthenticationIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSelectInvalidKey() {

	ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(),
			prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "2")));

	RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			clientHttpRequestFactory);
	ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate);

	assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(authentication::login);
}
 
Example #11
Source File: RequestCompressionPluginTest.java    From riptide with MIT License 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(RequestFactorySource.class)
void shouldBackOffIfAlreadyEncoded(final ClientHttpRequestFactory factory) {
    driver.addExpectation(onRequestTo("/")
                    .withMethod(POST)
                    .withHeader("Content-Encoding", "custom") // not handled by Jetty
                    .withoutHeader("X-Content-Encoding")
                    .withBody(equalTo("{}"), "application/json"),
            giveResponse("", "text/plain"));

    final Http http = buildHttp(factory, new RequestCompressionPlugin());
    http.post("/")
            .header(CONTENT_ENCODING, "custom")
            .contentType(MediaType.APPLICATION_JSON)
            .body(new HashMap<>())
            .call(pass())
            .join();
}
 
Example #12
Source File: KubernetesHashicorpVaultClientAuthenticationProvider.java    From knox with Apache License 2.0 5 votes vote down vote up
private RestOperations getRestOperations(Map<String, String> properties) throws Exception {
  String vaultAddress = properties.get(HashicorpVaultAliasService.VAULT_ADDRESS_KEY);
  VaultEndpoint vaultEndpoint = VaultEndpoint.from(new URI(vaultAddress));
  VaultEndpointProvider vaultEndpointProvider = SimpleVaultEndpointProvider.of(vaultEndpoint);
  ClientOptions clientOptions = new ClientOptions();
  SslConfiguration sslConfiguration = SslConfiguration.unconfigured();
  ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(
      clientOptions, sslConfiguration);
  return VaultClients.createRestTemplate(vaultEndpointProvider, clientHttpRequestFactory);
}
 
Example #13
Source File: ApiConfig.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);//单位为ms
    factory.setConnectTimeout(5000);//单位为ms
    return factory;
}
 
Example #14
Source File: DefaultRiptideRegistrar.java    From riptide with MIT License 5 votes vote down vote up
private String registerClientHttpRequestFactory(final String id, final Client client) {
    return registry.registerIfAbsent(id, ClientHttpRequestFactory.class, () -> {
        log.debug("Client [{}]: Registering RestAsyncClientHttpRequestFactory", id);
        return genericBeanDefinition(ApacheClientHttpRequestFactory.class)
                .addConstructorArgReference(registerHttpClient(id, client))
                .addConstructorArgValue(client.getConnections().getMode());
    });
}
 
Example #15
Source File: RestTemplateConfig.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);
    factory.setConnectTimeout(5000);
    return factory;
}
 
Example #16
Source File: RestTemplateConfig.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);//ms
    factory.setConnectTimeout(15000);//ms
    return factory;
}
 
Example #17
Source File: HashicorpKeyVaultServiceFactoryUtilTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void createClientHttpRequestFactory() {
    ClientOptions clientOptions = mock(ClientOptions.class);
    SslConfiguration sslConfiguration = mock(SslConfiguration.class);

    SslConfiguration.KeyStoreConfiguration keyStoreConfiguration = mock(SslConfiguration.KeyStoreConfiguration.class);
    when(sslConfiguration.getKeyStoreConfiguration()).thenReturn(keyStoreConfiguration);
    when(sslConfiguration.getTrustStoreConfiguration()).thenReturn(keyStoreConfiguration);

    when(clientOptions.getConnectionTimeout()).thenReturn(Duration.ZERO);
    when(clientOptions.getReadTimeout()).thenReturn(Duration.ZERO);

    ClientHttpRequestFactory result = util.createClientHttpRequestFactory(clientOptions, sslConfiguration);

    assertThat(result).isInstanceOf(OkHttp3ClientHttpRequestFactory.class);
}
 
Example #18
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	HttpClientBuilder httpClientBuilder = HttpClients.custom();

	httpClientBuilder.setRoutePlanner(
			new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

	if (hasSslConfiguration(sslConfiguration)) {

		SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration));
		SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
		httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
		httpClientBuilder.setSSLContext(sslContext);
	}

	RequestConfig requestConfig = RequestConfig.custom()
			//
			.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) //
			.setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) //
			.setAuthenticationEnabled(true) //
			.build();

	httpClientBuilder.setDefaultRequestConfig(requestConfig);

	// Support redirects
	httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

	return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
Example #19
Source File: RestTemplateConfig.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * init httpRequestFactory.
 * 
 * @return
 */
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(20000);
    factory.setConnectTimeout(5000);
    return factory;
}
 
Example #20
Source File: ClientHttpRequestFactoryFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options) throws GeneralSecurityException {

			HttpClientBuilder httpClientBuilder = HttpClients.custom();

			if (usingCustomCerts(options)) {
				SSLContext sslContext = sslCertificateUtils.getSSLContext(options.getCaCertFiles());
				SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

				httpClientBuilder.setSSLSocketFactory(sslSocketFactory).setSSLContext(sslContext);
			}
			else {
				httpClientBuilder.setSSLContext(SSLContext.getDefault()).useSystemProperties();
			}

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

			if (options.getConnectionTimeout() != null) {
				requestConfigBuilder.setConnectTimeout(options.getConnectionTimeoutMillis());
			}
			if (options.getReadTimeout() != null) {
				requestConfigBuilder.setSocketTimeout(options.getReadTimeoutMillis());
			}

			httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

			return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
		}
 
Example #21
Source File: VaultTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link VaultTemplate} with a {@link VaultEndpointProvider},
 * {@link ClientHttpRequestFactory} and {@link SessionManager}. This constructor does
 * not use a {@link ClientAuthentication} mechanism. It is intended for usage with
 * Vault Agent to inherit Vault Agent's authentication without using the
 * {@link VaultHttpHeaders#VAULT_TOKEN authentication token header}.
 * @param endpointProvider must not be {@literal null}.
 * @param requestFactory must not be {@literal null}.
 * @since 2.2.1
 */
public VaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory) {

	Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null");
	Assert.notNull(requestFactory, "ClientHttpRequestFactory must not be null");

	RestTemplate restTemplate = doCreateRestTemplate(endpointProvider, requestFactory);

	this.sessionManager = NoSessionManager.INSTANCE;
	this.dedicatedSessionManager = false;
	this.statelessTemplate = restTemplate;
	this.sessionTemplate = restTemplate;
}
 
Example #22
Source File: SpringCloudSecondaryConfiguration.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
@org.springframework.context.annotation.Bean("compensableRestTemplate")
public RestTemplate transactionTemplate(@Autowired ClientHttpRequestFactory requestFactory) {
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setRequestFactory(requestFactory);

	SpringCloudBeanRegistry registry = SpringCloudBeanRegistry.getInstance();
	registry.setRestTemplate(restTemplate);

	return restTemplate;
}
 
Example #23
Source File: ClientHttpRequestFactoryFactoryTests.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void okHttp3ClientCreated() throws Exception {
	ClientHttpRequestFactory factory = OkHttp3.usingOkHttp3(new ClientOptions());

	assertThat(factory).isInstanceOf(OkHttp3ClientHttpRequestFactory.class);

	((DisposableBean) factory).destroy();
}
 
Example #24
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void httpComponentsClientShouldWork() throws Exception {

	ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions(),
			Settings.createSslConfiguration());
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #25
Source File: RestTemplateConfig.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    //单位为ms
    factory.setReadTimeout(5000);
    //单位为ms
    factory.setConnectTimeout(5000);
    return factory;
}
 
Example #26
Source File: RestTemplateConfig.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);//ms
    factory.setConnectTimeout(15000);//ms
    return factory;
}
 
Example #27
Source File: TestRestTemplateFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static void initializeClientHttpRequestFactory(SslConfiguration sslConfiguration) throws Exception {

		if (factoryCache.get() != null) {
			return;
		}

		final ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory
				.create(new ClientOptions(), sslConfiguration);

		if (factoryCache.compareAndSet(null, clientHttpRequestFactory)) {

			if (clientHttpRequestFactory instanceof InitializingBean) {
				((InitializingBean) clientHttpRequestFactory).afterPropertiesSet();
			}

			if (clientHttpRequestFactory instanceof DisposableBean) {

				Runtime.getRuntime().addShutdownHook(new Thread("ClientHttpRequestFactory Shutdown Hook") {

					@Override
					public void run() {
						try {
							((DisposableBean) clientHttpRequestFactory).destroy();
						}
						catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		}
	}
 
Example #28
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	requestFactory = mock(ClientHttpRequestFactory.class);
	request = mock(ClientHttpRequest.class);
	response = mock(ClientHttpResponse.class);
	errorHandler = mock(ResponseErrorHandler.class);
	converter = mock(HttpMessageConverter.class);
	template = new RestTemplate(Collections.singletonList(converter));
	template.setRequestFactory(requestFactory);
	template.setErrorHandler(errorHandler);
}
 
Example #29
Source File: RestTemplateConfig.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);
    factory.setConnectTimeout(15000);
    return factory;
}
 
Example #30
Source File: RestTemplateConfig.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);//单位为ms
    factory.setConnectTimeout(5000);//单位为ms
    return factory;
}