Skip to main content

Java OKHttp Library: How to Send POST Requests

In this guide for The Java Web Scraping Playbook, we will look at how to make POST requests with the Java OKHttp Version 4.

In this guide we will walk you through the most common ways of sending POST requests with Java OKHttp Library:

Let's begin...


POST JSON Data Using Java OKHttp Library

A common scenario for using POST requests is to send JSON data to an API endpoint, etc. Here we break down how to make POST requests this with Java OKHttp Library.

Before you can make POST requests with Java OKHttp Library, you need to import all the required classes from this library.

import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

Note we are importing our classes from okhttp3 package even though we're using v4 of the library. That's because the same package naming from version 3.x has continued into version 4.x.


Now inside the main code, initialize requestUrl and jsonData variables.

String requestUrl = "https://httpbin.org/post";
String jsonData = "{ \"key\": \"value\" }";

After that use OkHttpClient.Builder constructor to create a new OkHttpClient builder. Call readTimeout method on the builder to set response timeout of 30 seconds. Finally chain call build method to build an instance of OkHttpClient named client. It's the client object that allows us to send requests to the server and receive responses.

 OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.build();
Simpler way to create OkHttpClient instance

If we didn't need to customize request timeout on client, we could simplify the above code to the following:

OkHttpClient client = new OkHttpClient();

You have to provide your request Content-Type in the form of MediaType object. Use MediaType.get factory method and provide "application/json" as an argument to create your contentType. Then initialize your request body by calling RequestBody.create method with jsonData string and contentType object.

MediaType contentType = MediaType.get("application/json");
RequestBody body = RequestBody.create(jsonData, contentType);

Next use Request.Builder constructor to create a new OkHttp Request builder. Then configure requestUrl and post body by calling url and post methods respectively. To actually create your request object based on the supplied configurations, simply call build method.

Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();

Finally to send the post request, just call client.newCall(request).execute method.

Response response = client.newCall(request).execute();
System.out.println("Response body: " + response.body().string());
How to Send POST Requests With Java OkHttp Library

Here's the entire code for making POST requests with Java OKHttp Library:

import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FormDataPostRequest {
public static void main(String[] args) throws Exception {
String requestUrl = "https://httpbin.org/post";
String jsonData = "{ \"key\": \"value\" }";

OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.build();

MediaType mediaType = MediaType.get("application/json");
RequestBody body = RequestBody.create(jsonData, mediaType);

Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();
Response response = client.newCall(request).execute();
System.out.println("Response body: " + response.body().string());
}
}

POST Form Data Using Java OKHttp Library

Another common use case for using POST requests is to send form data to an API endpoint. In this section, we'll see how we can make post request with the following formData:

String formData = "key1=value1&key2=value2";

To make form data POST requests with OKHttp, initialize contentType object by calling MediaType.get method with "application/x-www-form-urlencoded" so that formData will indeed be picked up as form data. Then create request body using RequestBody.create(formData, contentType) and pass it to post method of request builder.

MediaType contentType = MediaType.get("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(formData, contentType);

Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();

Here's the full code sample:

// imports have been left out here

public class FormDataPostRequest {
public static void main(String[] args) throws Exception {
String requestUrl = "https://httpbin.org/post";
String formData = "key1=value1&key2=value2";

OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.build();

MediaType contentType = MediaType.get("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(formData, contentType);

Request request = new Request.Builder()
.url(requestUrl)
.post(body)
.build();
Response response = client.newCall(request).execute();
System.out.println("Response body: " + response.body().string());
}
}

More Web Scraping Tutorials

So that's how you can send POST requests using Java OKHttp Library.

If you would like to learn more about Web Scraping, then be sure to check out The Web Scraping Playbook.

Or check out one of our more in-depth guides: