---
title: "How to Use OkHttp in Java (With Code Examples)"
description: "Master efficient networking in Java with OkHttp. We’ll cover practical tips and best practices for developers."
url: "https://iproyal.com/blog/okhttp-java/"
---

- [EN - English](https://iproyal.com/)
   
  [中文 - Chinese](https://iproyal.cn/)

[Book a Demo](https://iproyal.com/request-a-demo/) [Create Account](https://dashboard.iproyal.com/register/) [Create Account](https://dashboard.iproyal.com/register/) [Login](https://dashboard.iproyal.com/login/) [Login](https://dashboard.iproyal.com/login/)

[Book a Demo](https://iproyal.com/request-a-demo/)

[Back to blog](https://iproyal.com/blog/)

# How to Use OkHttp in Java (With Code Examples)

[Marijus Narbutas](https://iproyal.com/blog/authors/marijus-narbutas/)

[Last updated - August 25, 2025 ‐ 5 min read](https://iproyal.com/blog/authors/marijus-narbutas/)

[Tutorials](https://iproyal.com/blog/category/tutorials/)

## 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.**

OkHttp is **a modern HTTP client that helps you send and receive HTTP requests easily.&#x20;**&#x57;hen 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,&#x20;**&#x61;nd 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.&#x20;**&#x59;ou 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.&#x20;**&#x4D;any 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&#x20;**&#x73;o 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.&#x20;**&#x49;f 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.&#x20;**&#x49;f you’re scraping websites, check out our guide on [Java web scraping without getting blocked ](https://iproyal.com/blog/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:

```xml
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>4.12.0</version>
</dependency>
```

**This will download the latest stable version of OkHttp.&#x20;**&#x59;ou 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:

```javascript
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
```

Then **sync your project so the library gets downloaded.&#x20;**&#x41;fter 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.&#x20;**&#x54;he 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.&#x20;**&#x4D;ake 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.&#x20;**&#x49;t sends a new request and prints the response body to the console:

```java
// 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.&#x20;**&#x41;gain, the code prints the response body so you can see what the server sent back:

```java
// 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,&#x20;**&#x77;hich 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.&#x20;**&#x54;hese 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 ](https://iproyal.com/blog/top-programming-languages-for-web-scraping/).

[Create Account](https://dashboard.iproyal.com/)

[Author](https://iproyal.com/blog/authors/marijus-narbutas/)

[Marijus Narbutas](https://iproyal.com/blog/authors/marijus-narbutas/)

[Senior Software Engineer](https://iproyal.com/blog/authors/marijus-narbutas/)

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 ](https://iproyal.com/blog/authors/marijus-narbutas/)[Meet all Writers](https://iproyal.com/blog/authors/)

Share on

### In This Article

- [What Is OkHttp in Java?](https://iproyal.com/blog/okhttp-java/#What-Is-OkHttp-in-Java)
- [OkHttp vs HTTP: What’s the Difference?](https://iproyal.com/blog/okhttp-java/#OkHttp-vs-HTTP:-What%E2%80%99s-the-Difference)
- [Setting Up OkHttp in Java](https://iproyal.com/blog/okhttp-java/#Setting-Up-OkHttp-in-Java)
- [Performing GET and POST Requests With OkHttp](https://iproyal.com/blog/okhttp-java/#Performing-GET-and-POST-Requests-With-OkHttp)
- [Conclusion](https://iproyal.com/blog/okhttp-java/#Conclusion)

Ready to get started?

[Register now](https://dashboard.iproyal.com/register/)

Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

## Related articles

[View all](https://iproyal.com/blog/category/tutorials/)

[Tutorials](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

## [The Most Common Payment Processing Obstacles and Solutions for SaaS Companies](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[Here are the most common payment processing obstacles SaaS companies face and the solution that helped us focus on growth and our services!](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[August 8, 2022](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[3 min read](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[Tutorials](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

## [Easy Programmatic SEO with WordPress](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[Our fourth and final entry in the pSEO series explains how to combine programmatic SEO with WordPress using plugins or code snippets.](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[March 30, 2023](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[10 min read](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[Tutorials](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

## [API for Dummies — The Coder’s and No-coder’s Guide](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[Learn API basics with this guide for coders and non-coders. Discover the different components of an API call.](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[June 1, 2023](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[11 min read](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)
