by BehindJava

How to Hit a HTTP POST API using JSON as a Request body in Java

Home » java » How to Hit a HTTP POST API using JSON as a Request body in Java

In this blog, we are going to learn about Hitting the HTTP POST API using JSON as a Request body in Java. Let’s create a URL that accepts the data via HTTP POST method. We can’t instantiate HttpURLConnection directly, as it’s an abstract class. To send request content, let’s enable the URLConnection object’s doOutput property to true. If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json.

In this program I’m hitting the weather API with the Latitude, Longitude and Unix Date and time stamp in the request body, in the response we are getting the weather details.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestCallWeatherApi {

	public static void main(String args[]) throws Exception {
		// Step 1
		URL url = new URL(
				"https://api.openweathermap.org/data/2.5/weather?q=India,in&appid=55464354438435435ssdwd5ss5d5sd");
		// Step 2
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		// Step 3
		con.setRequestMethod("POST");
		// Step 4
		con.setRequestProperty("Content-Type", "application/json");
		// Step 5
		con.setDoOutput(true);
		// Step 6
		String jsonInputString = "{\r\n" + "    \"track\": [\r\n" + "        {\r\n"
				+ "            \"lat\": 14.4426,\r\n" + "            \"lon\": 79.9865,\r\n"
				+ "            \"dt\": 1667859843\r\n" + "        }\r\n" + "    ]\r\n" + "}";

		try (OutputStream os = con.getOutputStream()) {
			byte[] input = jsonInputString.getBytes("utf-8");
			os.write(input, 0, input.length);

			// Step 7
			try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
				StringBuilder response = new StringBuilder();
				String responseLine = null;
				while ((responseLine = br.readLine()) != null) {
					response.append(responseLine.trim());
				}
				System.out.println(response.toString());
			}
		}
	}
}

Output:

{
    "coord": {
        "lon": 77,
        "lat": 20
    },
    "weather": [
        {
            "id": 804,
            "main": "Clouds",
            "description": "overcast clouds",
            "icon": "04d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 298.82,
        "feels_like": 298.59,
        "temp_min": 298.82,
        "temp_max": 298.82,
        "pressure": 1017,
        "humidity": 44,
        "sea_level": 1017,
        "grnd_level": 962
    },
    "visibility": 10000,
    "wind": {
        "speed": 1.93,
        "deg": 107,
        "gust": 2
    },
    "clouds": {
        "all": 94
    },
    "dt": 1667881214,
    "sys": {
        "country": "IN",
        "sunrise": 1667869007,
        "sunset": 1667909682
    },
    "timezone": 19800,
    "id": 1269750,
    "name": "India",
    "cod": 200
}

Step 1

Let’s make a URL object with a target URI string that takes JSON data through HTTP POST.

Step 2

We may acquire the HttpURLConnection object by using the openConnection function on the above URL object.
We can’t manually instantiate HttpURLConnection because it’s an abstract class.

Step 3

To hit a POST request, we must set the request method to POST.

Step 4

To deliver the request body in JSON format, set the “content-type” request header to “application/json” This option must be set if the request body is to be sent in JSON format.
If this is not done, the server returns the HTTP status code “400-bad request”.

Step 5

To convey request content, set the doOutput property of the URLConnection object to true.
We won’t be able to publish stuff to the connection output stream otherwise.

Step 6

Declare a JSON String in which we are going to initialize our request body.
Obtain the input stream in order to read the response content. Remember to use try-with-resources to automatically end the response stream.

Step 7

Read the whole response content and output the final response to a string.

Note: If the answer is in JSON format, parse it using any third-party JSON parser such as Jackson library, Gson, or org.json.