Spring Boot API Call using OkHttp
Last Updated :
24 Apr, 2025
OkHttp is pretty smart when it comes to dealing with tricky network situations. It quietly bounces back from common connection hiccups and even tries different addresses if the first attempt doesn't work. This becomes crucial when you're dealing with situations that use both IPv4 and IPv6 or when your services are set up in backup data centers. In this article, you are going to explore how you can use OkHttp in your Spring Boot application.
Prerequisites:
What is OkHttp?
OkHttp stands out as an HTTP client that prioritizes efficiency by default:
- HTTP/2 Support: Allows multiple requests to the same host to share a socket, enhancing performance.
- Connection Pooling: Reduces latency for requests, particularly beneficial in scenarios where HTTP/2 is not available.
- Transparent GZIP: Compresses download sizes seamlessly through GZIP, contributing to optimized data transfer.
- Response Caching: Bypasses the network for repeat requests, improving efficiency.
- Resilience: OkHttp adeptly manages challenging network conditions, silently recovering from common connection issues. It intelligently attempts alternate addresses if the initial connection fails, crucial for IPv4+IPv6 and services in redundant data centers.
- Modern TLS Support: OkHttp is equipped with contemporary TLS features, including TLS 1.3, ALPN, and certificate pinning. It offers configuration options for versatile connectivity.
Using OkHttp is straightforward. Its request/response API employs fluent builders and immutability, facilitating ease of use. Whether you prefer synchronous blocking calls or asynchronous calls with callbacks, OkHttp accommodates both styles seamlessly.
Implementation of OkHttp in an Spring Boot Application
Let's get started with the implementation part to create a simple Spring Boot application that make API calls using OkHttp.
Step-by-step Implementation
Step 1: Create a new Spring Boot Project
To create a new Spring Boot Protect, you can use Spring Initializer (https://start.spring.io/) or your preferred IDE. In the dependencies you need to select "Spring Web" dependency, as it will be useful for creating REST endpoints.

Step 2: Add OkHttp Dependency
Now we need to add OkHttps dependency in the pom.xml file, paste the below code in the pom.xml or you can use the updated version from Maven website:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
Now you are all set to write some code to use OkHttp in your Spring Boot Project.
Step 3: Create a Service for API Calls
Firstly, create a service class that will be responsible to handle API calls using OkHttp. For example, create a class named ApiService and write the below code inside the class.
Java
import okhttp3.*;
import java.io.IOException;
@Service
public class ApiService {
private final OkHttpClient client = new OkHttpClient();
// Get Request
public String makeGetRequest(String apiUrl) throws IOException {
Request request = new Request.Builder().url(apiUrl).build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected response: " + response.code());
}
}
}
// Post Request
public String makePostRequest(String apiUrl, String requestBody) throws IOException {
RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/json"));
Request request = new Request.Builder().url(apiUrl).post(body).build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected response: " + response.code());
}
}
}
}
This file consists of two service methods:
- makeGetRequest(String apiUrl) - makeGetRequest(String) method handles GET request API call with OkHttp.
- makePostRequest(String apiUrl, String requestBody) - This method handles POST request API call with OkHttp and sends the data to the server.
Step 4: Create a Controller
Create a Spring MVC controller that will expose endpoints for triggering the API call. For example, create a class named ApiController. In this article, we are using https://jsonplaceholder.typicode.com dummy API.
Java
import okhttp3.*;
import java.io.IOException;
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private ApiService apiService;
// End-point for GET Request
@GetMapping("/get-example")
public String getExample() {
String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
try {
String apiResponse = apiService.makeGetRequest(apiUrl);
return "GET Response: " + apiResponse;
} catch (IOException e) {
e.printStackTrace();
return "While making GET request, getting Error: " + e.getMessage();
}
}
// End-point for POST Request
@PostMapping("/post-example")
public String postExample() {
String apiUrl = "https://jsonplaceholder.typicode.com/posts";
// This is the request body
String requestBody = "{\'title\': \'foo\',\'body\': \'bar\',\'userId\': 1}";
try {
String apiResponse = apiService.makePostRequest(apiUrl, requestBody);
return "POST Response: " + apiResponse;
} catch (IOException e) {
e.printStackTrace();
return "While making POST request, getting Error: " + e.getMessage();
}
}
}
In the above code, you have two methods:
- getExample() - getExample() method is invoked when a GET request is fired for /api/get-example end-point.
- postExample() - This method is invoked when a POST request is fired for /api/post-example end-point. In this method there is one variable named requestBody of String type, in this variable the request body has been defined to send with the request.
Step 5: Run the Application
To run your Spring Boot application, you can run below Maven command in the terminal, or you can also use the IDE to run the application:
mvn spring-boot:run

Step 6: Test the API Call
Finally, to test the API call you can use your browser, a tool like cURL, or Postman to make GET/POST and other requests to the endpoints. You should see the API response or an error message.
Let's test the /api/get-example endpoint:
Open Postman, then enter the URL like - http://localhost:8080/api/get-example and select GET request from left dropdown, finally click on send button, now a response will be generated.

Now test the /api/post-example endpoint:
Open Postman, then enter the URL like - http://localhost:8080/api/post-example and select POST request from left dropdown, finally click on send button, now a response will be generated.
Remember to replace the example URLs with the actual URLs of the APIs you want to call.
Similar Reads
Pet Clinic Application using Spring Boot
Every Pet clinic need Pet Clinic application becaue it plays an important role in the real world in saving pets from different situations. Mostly, online Pet Clinic applications are developed with the required business logic. Here, we've created a simple Spring Boot Application for the Pet Clinic Ap
14 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
10 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of th
4 min read
Spring Boot - Versioning a REST API
API Versioning is a defined process of making or managing changes to an API. These changes can be made transparently without interrupting the clients. When users have permission to decide whether they can conveniently upgrade to the latest version of API and clearly state the changes made is known a
3 min read
Spring Boot â Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate diffe
5 min read
Spring Boot - Admin Client
In Sprint Boot, Admin and Client can be implemented so that the client can be registered with the server, and then the server maintains the client's service health and availability, scales up the service, and also measures the representation of the client. Spring Boot Admin ServerThe Admin Server ca
4 min read
Rate Limiting a Spring API Using Bucket4j
Rate limiting is a technique used to control the number of incoming requests to a server within a specified time frame. It helps protect APIs from being overwhelmed by too many requests, whether intentional (DDoS attacks) or accidental (due to bugs or misconfigured clients). One of the popular libra
7 min read
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
How to Create Todo List API using Spring Boot and MySQL?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
6 min read