Reading:
POST Request in Java

POST Request in Java

Metamug
POST Request in Java

In this article, we will understand how to send POST request in java. We will be using popular client library okhttp.

RequestBody for POST request

POST request requires a body in contrast to a GET request. OKHttp has a good api to call post requests. The only different between GET request and POST request is the use of RequestBody.

The RequestBody object is constructed using the builder pattern. In the below example we have added a single form parameter to the api request.

RequestBody requestBody = new FormBody.Builder()
    .add("search", "Jurassic Park")
    .build();

The below request send the POST request with content type application/x-www-form-urlencoded.

MultiPart Form Body

In the case of sending the request with a multipart body, we must set type as MultipartBody.Form

RequestBody requestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("info", queries)
    .addFormDataPart("appid", "covid19")
    .addFormDataPart("type", "querybyuser")
    .build();

JSON Body

Building a Request body with a JSON is the easiest task.

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(json, JSON);

Building Request

The request can be built using the RequestBody object

Request request = new Request.Builder()
                .url(BASE_URL + "/opendata/v1.0/coronavirus")
                .addHeader("Authorization", "Bearer 4eXXXXXXXXXXXXXXXXXXXXb")
                .post(requestBody)
                .build();

Handling Response

POST request response handling is similar to a GET request response. If it is a JSON response, it can be parsed using a JSON library like org.json

try (Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            JSONObject json = new JSONObject(body.string());
            JSONArray array = (JSONArray) json.get("max_count");
            JSONObject firstElement = (JSONObject) array.get(0);
            count = (Integer) firstElement.get("total");
        }

Final Code


import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

public class APIHandler {
    private static final String BASE_URL = "https://api.metamug.com";
    OkHttpClient client = new OkHttpClient();

    public int sendQueries(String queries) throws IOException {
        int count = 0;
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("info", queries)
                .addFormDataPart("appid", "covid19")
                .addFormDataPart("type", "querybyuser")
                .build();

        Request request = new Request.Builder()
                .url(BASE_URL + "/opendata/v1.0/coronavirus")
                .addHeader("Authorization", "Bearer 4eXXXXXXXXXXXXXXXXXXXXb")
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            JSONObject json = new JSONObject(body.string());
            JSONArray array = (JSONArray) json.get("max_count");
            JSONObject firstElement = (JSONObject) array.get(0);
            count = (Integer) firstElement.get("total");
        }
        return count;
    }

}

Maven Dependency

For this example we have used following maven dependencies of OKHTTP and JSON

<dependency>
    <groupId>com.squareup.okhttp</groupId>
    <artifactId>okhttp</artifactId>
    <version>2.7.5</version>
</dependency>

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

You can find the examples on OKHttp's official website



Comments

Post a comment
Icon For Arrow-up