OkHttp POST Request Java Example

In this post, we will create an OkHttp POST HTTP request example in Java.
OkHTTP is an open source project designed to be an efficient HTTP client for Android and Java applications.
OkHttp supports Android 5.0+ (API level 21+) and Java 1.8+. In this article, we will write a code using Java 1.8+.

Maven Dependency

Let’s first add the library as a dependency into the pom.xml:
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>
To see the latest dependency of this library check out the page on Maven Central.

OkHttp POST Request Java Example

In this example, we will make a POST HTTP client request for spring boot CRUD example project. This spring boot crud example project is deployed and up and running. Refer to this article - https://www.javaguides.net/2018/09/spring-boot-2-hibernate-5-mysql-crud-rest-api-tutorial.html

package com.javaguides.okhttp.tutorial.crud;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPost {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static void main(String[] args) throws IOException {
        OkHttpPost example = new OkHttpPost();
        String json = "{\r\n" +
            " \"firstName\" : \"Ramesh\",\r\n" +
            " \"lastName\" : \"Fadatare\",\r\n" +
            " \"emailId\" : \"[email protected]\"\r\n" +
            "}";
        String response = example.post("http://localhost:8080/api/v1/employees", json);
        System.out.println(response);
    }
}
Below diagram shows the screenshot of source code as well as output:

Basic POST Request Example

In this simple example, we build a RequestBody to send two parameters – “username” and “password” – with the POST request:
package com.javaguides.okhttp.tutorial;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostRequestParameterExample {

    private static final String BASE_URL = "http://localhost:8080/spring-rest";

    static OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        final RequestBody formBody = new FormBody.Builder()
            .add("username", "test")
            .add("password", "test").build();

        final Request request = new Request.Builder()
            .url(BASE_URL + "/users")
            .post(formBody).build();

        final Call call = client.newCall(request);
        final Response response = call.execute();
        System.out.println(response);
    }
}

POST Request with JSON Example

In this example we’ll send a POST request with a JSON as RequestBody:
package com.javaguides.okhttp.tutorial;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostExample {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    String bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE'," + "'name':'Bowling'," + "'round':4," + "'lastSaved':1367702411696," +
            "'dateStarted':1367702378785," + "'players':[" + "{'name':'" + player1 +
            "','history':[10,8,6,7,8],'color':-13388315,'total':39}," + "{'name':'" + player2 +
            "','history':[6,10,5,10,10],'color':-48060,'total':41}" + "]}";
    }

    public static void main(String[] args) throws IOException {
        OkHttpPostExample example = new OkHttpPostExample();
        String json = example.bowlingJson("Jesse", "Jake");
        String response = example.post("http://www.roundsapp.com/post", json);
        System.out.println(response);
    }
}
Output:
http://www.roundsapp.com/393141003
Note that the output response URL contains an ID for a newly created resource.

Multipart POST Request

In this example, we’ll send a POST Multipart Request. We need to build our RequestBody as MultipartBody to post a File, a username, and a password:
package com.javaguides.okhttp.tutorial;

import java.io.File;
import java.io.IOException;

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

public class OkHttpPostUploadFileExample {

    private static final String BASE_URL = "http://localhost:8080/spring-rest";

    static OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {

        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("username", "test").addFormDataPart("password", "test")
            .addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"),
                new File("src/test/resources/test.txt")))
            .build();

        Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();

        Call call = client.newCall(request);
        Response response = call.execute();
        System.out.println(response.code());
    }
}
Check out https://www.javaguides.net/2019/05/okhttp-get-post-put-and-delete-request-java-examples.html.

Comments