org.springframework.http.client.OkHttp3ClientHttpRequestFactory Java Examples

The following examples show how to use org.springframework.http.client.OkHttp3ClientHttpRequestFactory. 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: OkHttpRestTemplateAutoConfiguration.java    From okhttp-spring-boot with MIT License 6 votes vote down vote up
@Bean
@Lazy
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder(ObjectProvider<HttpMessageConverters> messageConverters,
                                               ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers,
                                               ObjectProvider<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers,
                                               OkHttpClient okHttpClient) {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    HttpMessageConverters converters = messageConverters.getIfUnique();
    if (converters != null) {
        builder = builder.messageConverters(converters.getConverters());
    }
    builder = addCustomizers(builder, restTemplateCustomizers, RestTemplateBuilder::customizers);
    builder = addCustomizers(builder, restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);

    builder = builder.requestFactory(() -> new OkHttp3ClientHttpRequestFactory(okHttpClient));

    return builder;
}
 
Example #2
Source File: DefaultRestExecutorFactory.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public RestExecutor createRestExecutor() {
	RestExecutorConfig config = this.restExecutorConfig;
	if(config==null){
		config = new RestExecutorConfig();
	}
	ExtRestTemplate restTemplate = null;
	if(RestUtils.isOkHttp3Present()){
		OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory();
		requestFactory.setConnectTimeout(config.getConnectTimeout());
		requestFactory.setReadTimeout(config.getReadTimeout());
		requestFactory.setWriteTimeout(config.getWriteTimeout());
		restTemplate = new ExtRestTemplate(requestFactory);
	}else{
		restTemplate = new ExtRestTemplate();
	}
	return restTemplate;
}
 
Example #3
Source File: OkHttpRestTemplateAutoConfiguration.java    From okhttp-spring-boot with MIT License 6 votes vote down vote up
@Bean
@Lazy
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder(ObjectProvider<HttpMessageConverters> messageConverters,
                                               ObjectProvider<RestTemplateCustomizer> restTemplateCustomizers,
                                               ObjectProvider<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers,
                                               OkHttpClient okHttpClient) {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    HttpMessageConverters converters = messageConverters.getIfUnique();
    if (converters != null) {
        builder = builder.messageConverters(converters.getConverters());
    }
    builder = addCustomizers(builder, restTemplateCustomizers, RestTemplateBuilder::customizers);
    builder = addCustomizers(builder, restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);

    builder = builder.requestFactory(() -> new OkHttp3ClientHttpRequestFactory(okHttpClient));

    return builder;
}
 
Example #4
Source File: HttpSyncDataService.java    From soul with Apache License 2.0 6 votes vote down vote up
private void start(final HttpConfig httpConfig) {
    // init RestTemplate
    OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory();
    factory.setConnectTimeout((int) this.connectionTimeout.toMillis());
    factory.setReadTimeout((int) HttpConstants.CLIENT_POLLING_READ_TIMEOUT);
    this.httpClient = new RestTemplate(factory);
    // It could be initialized multiple times, so you need to control that.
    if (RUNNING.compareAndSet(false, true)) {
        // fetch all group configs.
        this.fetchGroupConfig(ConfigGroupEnum.values());
        // one thread for listener, another one for fetch configuration data.
        this.executor = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                SoulThreadFactory.create("http-long-polling", true));
        // start long polling.
        this.executor.execute(new HttpLongPollingTask());
    } else {
        log.info("soul http long polling was started, executor=[{}]", executor);
    }
}
 
Example #5
Source File: SpringRestTemplateInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters()
public static Iterable<Supplier<ClientHttpRequestFactory>> data() {
    return Arrays.asList(
        SimpleClientHttpRequestFactory::new,
        OkHttp3ClientHttpRequestFactory::new,
        HttpComponentsClientHttpRequestFactory::new);
}
 
Example #6
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 #7
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 #8
Source File: AsyncRestTemplateBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override protected AsyncRestTemplate newClient(HttpTracing httpTracing) {
  OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(ok);
  AsyncRestTemplate result = new AsyncRestTemplate(factory);
  result.setInterceptors(Collections.singletonList(
    TracingAsyncClientHttpRequestInterceptor.create(httpTracing
    )));
  return result;
}
 
Example #9
Source File: RestTemplateBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override protected RestTemplate newClient(HttpTracing httpTracing) {
  OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(ok);
  RestTemplate result = new RestTemplate(factory);
  result.setInterceptors(Collections.singletonList(
    TracingClientHttpRequestInterceptor.create(httpTracing
    )));
  return result;
}
 
Example #10
Source File: OkClientHttpRequestFactoryCreator.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpRequestFactory createRequestFactory(TimeoutConfiguration configuration) {
    OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory(httpClient);
    requestFactory.setConnectTimeout(toMillis(configuration.getConnection()));
    requestFactory.setReadTimeout(toMillis(configuration.getRead()));
    requestFactory.setWriteTimeout(toMillis(configuration.getWrite()));
    return requestFactory;
}
 
Example #11
Source File: Main.java    From fahrschein with Apache License 2.0 5 votes vote down vote up
private static void subscriptionListenSpringAdapter(ObjectMapper objectMapper, Listener<SalesOrderPlaced> listener) throws IOException {

        final OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(2, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(2, 5*60, TimeUnit.SECONDS))
                .certificatePinner(new CertificatePinner.Builder()
                        .add(NAKADI_URI.getHost(), "sha256/KMUmME9xy7BKVUZ80VcmQ75zIZo16IZRTqVRYHVZeWY=")
                        .build())
                .build();

        final OkHttp3ClientHttpRequestFactory clientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory(client);
        final SpringRequestFactory requestFactory = new SpringRequestFactory(clientHttpRequestFactory);

        final NakadiClient nakadiClient = NakadiClient.builder(NAKADI_URI)
                .withRequestFactory(requestFactory)
                .withAccessTokenProvider(new ZignAccessTokenProvider())
                .build();

        final Subscription subscription = nakadiClient.subscription("fahrschein-demo", SALES_ORDER_SERVICE_ORDER_PLACED)
                .withConsumerGroup("fahrschein-demo")
                .readFromEnd()
                .subscribe();

        nakadiClient.stream(subscription)
                .withObjectMapper(objectMapper)
                .listen(SalesOrderPlaced.class, listener);
    }
 
Example #12
Source File: RestTemplateIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Parameters
public static Iterable<? extends ClientHttpRequestFactory> data() {
	return Arrays.asList(
			new SimpleClientHttpRequestFactory(),
			new HttpComponentsClientHttpRequestFactory(),
			new Netty4ClientHttpRequestFactory(),
			new OkHttp3ClientHttpRequestFactory()
	);
}
 
Example #13
Source File: ValidationConfiguration.java    From recaptcha-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected RestTemplate createRestTemplate() {
    Timeout timeout = recaptcha.getValidation().getTimeout();
    OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory();
    requestFactory.setConnectTimeout(toMilliseconds(timeout.getConnect()));
    requestFactory.setReadTimeout(toMilliseconds(timeout.getRead()));
    requestFactory.setWriteTimeout(toMilliseconds(timeout.getWrite()));
    return new RestTemplate(requestFactory);
}
 
Example #14
Source File: RestTemplateIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Parameters
public static Iterable<? extends ClientHttpRequestFactory> data() {
	return Arrays.asList(
			new SimpleClientHttpRequestFactory(),
			new HttpComponentsClientHttpRequestFactory(),
			new org.springframework.http.client.Netty4ClientHttpRequestFactory(),
			new OkHttp3ClientHttpRequestFactory()
	);
}
 
Example #15
Source File: Oauth2AuthenticationApplication.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public RestTemplate restTemplate() {
	return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
 
Example #16
Source File: AsyncRestTemplateBenchmarks.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected AsyncRestTemplate newClient() {
  return new AsyncRestTemplate(new OkHttp3ClientHttpRequestFactory(ok));
}
 
Example #17
Source File: RestTemplateBenchmarks.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected RestTemplate newClient() {
  return new RestTemplate(new OkHttp3ClientHttpRequestFactory(ok));
}
 
Example #18
Source File: ExtRestTemplate.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public ExtRestTemplate(){
	this(RestUtils.isOkHttp3Present()?new OkHttp3ClientHttpRequestFactory():null);
}
 
Example #19
Source File: RestTemplateConfig.java    From spring-boot-tutorials with Apache License 2.0 4 votes vote down vote up
@Bean
public OkHttp3ClientHttpRequestFactory okHttp3ClientHttpRequestFactory(OkHttpClient okHttpClient) {
    OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(okHttpClient);
    return factory;
}
 
Example #20
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
static ClientHttpRequestFactory usingOkHttp3(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	Builder builder = new Builder();

	if (hasSslConfiguration(sslConfiguration)) {

		TrustManager[] trustManagers = getTrustManagers(sslConfiguration);

		if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
			throw new IllegalStateException(
					"Unexpected default trust managers:" + Arrays.toString(trustManagers));
		}

		X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
		SSLContext sslContext = getSSLContext(sslConfiguration, trustManagers);

		builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
	}

	builder.connectTimeout(options.getConnectionTimeout().toMillis(), TimeUnit.MILLISECONDS)
			.readTimeout(options.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS);

	return new OkHttp3ClientHttpRequestFactory(builder.build());
}
 
Example #21
Source File: Oauth2AuthenticationApplication.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public RestTemplate restTemplate() {
	return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
 
Example #22
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
@Test
void okHttp3ClientShouldWork() throws Exception {

	ClientHttpRequestFactory factory = OkHttp3.usingOkHttp3(new ClientOptions(), Settings.createSslConfiguration());
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

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

	((DisposableBean) factory).destroy();
}