Home > Spring > Spring Boot > Configure Spring RestTemplate with OkHttp3 in Spring Boot Application

Configure Spring RestTemplate with OkHttp3 in Spring Boot Application

Okhttp3 is a popular HTTP client implementation for Java and we can easily embed it in our Spring Boot RestTemplate abstraction.

Below is the Bean definition which binds the instance of Okhttp3 client with RestTemplate.

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

public class OkHttpConfiguration {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());

    private static final int HTTP_MAX_IDLE = 20;
    private static final int HTTP_KEEP_ALIVE = 20;
    private static final int HTTP_CONNECTION_TIMEOUT = 30;

    public RestTemplate okhttp3Template() {
        RestTemplate restTemplate = new RestTemplate();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        ConnectionPool okHttpConnectionPool = new ConnectionPool(HTTP_MAX_IDLE, HTTP_KEEP_ALIVE,
        builder.connectTimeout(HTTP_CONNECTION_TIMEOUT, TimeUnit.SECONDS);

        restTemplate.setRequestFactory(new OkHttp3ClientHttpRequestFactory(builder.build()));

        return restTemplate;

Now to integrate in our implementation class we just need to autowire the Resttemplate to use this customized Okhttp3 based resttemplate.

private RestTemplate okhttp3Template;

How to use RestTemplate using OkHttp3 in the Spring Boot Application

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HttpOperationUtils {

	private Logger LOGGER = LoggerFactory.getLogger(getClass());

	private RestTemplate okhttp3Template;

	private Map<String, Object> callUsingOkHttp(String source) throws RestClientException, URISyntaxException {
		Map<String, Object> okHttpRestExecute = null;
		try {
			RequestCallback requestCallback = req -> req.getHeaders().add("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");

			ResponseExtractor<Map<String, Object>> responseExtractor = response -> {
				Map<String, Object> res = new HashMap<String, Object>();
				res.put("status", response.getStatusCode());
				res.put("header", response.getHeaders());
				res.put("body", response.getBody());

				return res;

			okHttpRestExecute = okhttp3Template.execute(new URI(source), HttpMethod.GET, requestCallback, responseExtractor);
		} catch (HttpClientErrorException e) {
			LOGGER.error("[Download file] okhttp failed to write:", e);
		return okHttpRestExecute;