How to Use OkHttp in Java (With Code Examples)


Marijus Narbutas
Key Takeaways
-
OkHttp simplifies how you create and send HTTP requests, including both GET and POST.
-
The Request.Builder and Request object pattern makes writing code easier and more readable.
-
Managing asynchronous requests, response headers, and response body becomes more efficient with OkHttpClient.
In This Article
OkHttp is a modern HTTP client that helps you send and receive HTTP requests easily. When you call an API, the answer comes back as a response body, and you can also inspect the response headers.
For each new request, using a new Request.Builder helps prevent reusing old settings you might not want anymore. An OkHttpClient can be customized with timeouts, interceptors, and caches, and you can create multiple clients for different configurations.
You build the request using the builder, then pass it to the OkHttpClient to execute and get a response.
What Is OkHttp in Java?
OkHttp is an open-source HTTP client for Java and Android apps that makes it easy to send web requests. It has advanced features like HTTP/2, connection pooling, transparent GZIP compression, caching, and automatic retries on certain types of network failures.
When you send a new request, OkHttp handles most of the networking for you. You use a Request.Builder to create a Request, where you define the URL, headers, and other options.
After you make the call using OkHttpClient, the library lets you read the HTTP responses and handle errors manually. Many other clients only support one style of call, but OkHttp supports both synchronous and asynchronous requests.
In simple terms, it wraps the complex network logic so you can focus on writing clean, readable code.
OkHttp vs HTTP: What’s the Difference?
The default HTTP client in Java is functional, but lacks flexibility. If you’ve ever tried sending a new request with it or adding query parameters, you know how much extra code it takes. It’s not exactly an efficient HTTP client.
Now, with the OkHttp client, it gets easier:
- It reuses connections automatically.
- It handles asynchronous requests.
- It’s more readable, especially when building a Request object with a Request.Builder.
- It offers better performance, especially when switching between multiple IP addresses using proxies during web scraping or IP testing.
OkHttpClient can be used with proxies to rotate IPs, which helps when managing sessions or avoiding rate limits. If you’re scraping websites, check out our guide on Java web scraping without getting blocked for more ideas.
Setting Up OkHttp in Java
Before you can send any HTTP requests with OkHttp, you need to add it to your Java project. Here’s how to do that using Maven or Gradle, depending on your tool. Eclipse IDE is a great tool if you want to just test out the code.
Maven Setup
If you use Maven, open your pom.xml file and add this inside the <dependencies>
section:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
This will download the latest stable version of OkHttp. You can now use OkHttpClient and all other features like Request.Builder, Request object, and more.
Gradle Setup
If your project uses Gradle, open build.gradle and add the following line to the dependencies block:
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
Then sync your project so the library gets downloaded. After that, you’re ready to make a new request.
Performing GET and POST Requests With OkHttp
Once you’ve added OkHttp to your project (using Maven or Gradle), you’re ready to write HTTP requests. The examples below go inside a Java class.
You can put them in a file like OkHttpGetExample.java or OkHttpPostExample.java inside your src/main/java folder, depending on how your project is set up.
Each example uses a main() method so you can run them directly to test things out. Make sure you’ve imported the needed OkHttp classes and are using Java 8 or later.
GET Request Example
This code performs a GET request to an API. It sends a new request and prints the response body to the console:
// Import OkHttp classes
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpGetExample {
public static void main(String[] args) {
// Step 1: Create an OkHttpClient instance (http client)
OkHttpClient client = new OkHttpClient();
// Step 2: Use Request.Builder to create a new GET request
Request request = new Request.Builder()
.url("https://api.example.com/data?user=123&active=true") // Set URL with query parameters
.build(); // Finish building the object
try {
// Step 3: Send the new request and get a response
Response response = client.newCall(request).execute();
// Step 4: Read and print the response body as a string
System.out.println(response.body().string()); // Always close response content after use
} catch (Exception e) {
// Handle error in case of a failed request
e.printStackTrace();
}
}
}
Save the above code in a file called OkHttpGetExample.java. Then compile it and run it from your terminal or your IDE (like IntelliJ or Eclipse). The program will send a GET request and print the response body to your screen.
The code shows how to:
- Create a new request using a Request.Builder.
- Include query parameters in the URL.
- Handle the response body safely.
POST Request Example
This example sends a POST request with some JSON data. Again, the code prints the response body so you can see what the server sent back:
// Import OkHttp classes
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpPostExample {
public static void main(String[] args) {
// Step 1: Create the client
OkHttpClient client = new OkHttpClient();
// Step 2: Define the data to send (JSON format)
String json = "{\"name\":\"Alice\", \"age\":25}";
// Step 3: Create a new request body with JSON and content type
RequestBody body = RequestBody.create(
json,
MediaType.get("application/json")
);
// Step 4: Build the new request using Request.Builder
Request request = new Request.Builder()
.url("https://api.example.com/users") // Target URL
.post(body) // Attach the request body to make it a post command
.build(); // Create the final object
try {
// Step 5: Send the new request and get a response
Response response = client.newCall(request).execute();
// Step 6: Print the response content to console
System.out.println(response.body().string()); // Important: close the response body when done
} catch (Exception e) {
// Handle any request failed error
e.printStackTrace();
}
}
}
Put this code into a file named OkHttpPostExample.java. You can run it just like the GET example. The console will show the response body sent by the server, which might be a confirmation message or user data.
In this POST request, you:
- Create a RequestBody with JSON data.
- Use a Request.Builder to make a new request with .post().
- Read the response body after sending it with the HTTP client.
Both examples use OkHttpClient to show real-world usage and how to build and send new requests. These are basic, but you can expand them to include headers, asynchronous requests, or even rotate between multiple IPs using proxies if needed.
Conclusion
Using OkHttp is a smart decision if you want cleaner, faster, and more flexible code when working with HTTP requests. It gives you more control when creating new requests, managing query parameters, and reading the HTTP responses.
If you’re working with APIs or scraping sites that require handling multiple IP addresses, make sure you check the best programming languages for web scraping .

Author
Marijus Narbutas
Senior Software Engineer
With more than seven years of experience, Marijus has contributed to developing systems in various industries, including healthcare, finance, and logistics. As a backend programmer who specializes in PHP and MySQL, Marijus develops and maintains server-side applications and databases, ensuring our website works smoothly and securely, providing a seamless experience for our clients. In his free time, he enjoys gaming on his PS5 and stays active with sports like tricking, running, and weight lifting.
Learn More About Marijus Narbutas