How to Send GET and POST Requests with OkHttp in Java

in #tool26 days ago

Networking isn’t just about sending requests; it’s about doing it cleanly, reliably, and quickly. Wrestling with verbose HTTP code in Java can be painful and time-consuming. OkHttp changes everything, making requests straightforward, responses predictable, and giving full control back to developers.
OkHttp is an open-source HTTP client for Java and Android. It handles the heavy lifting—HTTP/2, connection pooling, automatic retries, GZIP compression, caching. You write the logic. It handles the network.

Why OkHttp Beats Java’s Default HTTP Client

Java’s built-in HTTP client works… barely. Need query parameters? Headers? Retry logic? Prepare for boilerplate.

OkHttp simplifies everything:

  • Connection reuse – faster and less resource-intensive.
  • Async ready – run multiple requests without blocking.
  • Readable syntaxRequest.Builder keeps your code clean.
  • Proxy support – perfect for testing, web scraping, or rotating IPs.

Combine OkHttp with proxies to rotate IPs and manage sessions. It’s a lifesaver for web scraping or API testing without triggering rate limits.

OkHttp Setup in Java

Before sending requests, add OkHttp to your project:

Maven:

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

Gradle:

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

Sync your project. Done. Ready to roll.

Handling GET Requests

GET requests fetch data. Simple, but powerful. Here’s how to do it:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpGetExample {
  public static void main(String[] args) {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
      .url("https://api.example.com/data?user=123andactive=true")
      .build();

    try {
      Response response = client.newCall(request).execute();
      System.out.println(response.body().string());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Key Takeaways:

  • Use Request.Builder for fresh requests every time.
  • Include query parameters directly in the URL.
  • Always handle the response body safely.

Handling POST Requests

POST requests let you send structured data, like JSON. Example:

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostExample {
  public static void main(String[] args) {
    OkHttpClient client = new OkHttpClient();

    String json = "{\"name\":\"Alice\", \"age\":25}";
    RequestBody body = RequestBody.create(json, MediaType.get("application/json"));

    Request request = new Request.Builder()
      .url("https://api.example.com/users")
      .post(body)
      .build();

    try {
      Response response = client.newCall(request).execute();
      System.out.println(response.body().string());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Practical Tips:

  • Wrap JSON in RequestBody.
  • Attach it using .post().
  • Always read the response to verify the server accepted your data.

Pro Tips for Advanced Usage

  • Headers and Auth: .header() and .addHeader() let you handle authentication cleanly.
  • Async Requests: .enqueue() avoids blocking your main thread.
  • Caching: Speed up repeated calls.
  • Retries: Configure OkHttp to retry automatically on network failure.
  • Proxy Rotation: Essential for scraping or testing multiple endpoints.

Even basic examples scale well when you apply these techniques.

Conclusion

OkHttp isn’t just convenient; it boosts productivity by reducing boilerplate, cleaning up code, and providing reliable networking. Integrating it makes GETs, POSTs, asynchronous calls, retries, caching, and proxy rotation feel effortless, delivering fast, predictable, and powerful network operations.