Free public REST API

Real REST API which is ready to handle your HTTP requests 24/7 for free. Can be used for your demo projects, testing, learning or even educating someone else. This REST API supports main HTTP methods such as GET, POST, PUT, DELETE and PATCH.


Send a POST request in Java


What is a POST Request?

A POST Request is one of the most popular HTTP methods which is used when you want to create a new resource that would store some data. The data which is sent as part of a POST request is usually called a request body. Depending on a REST API and on an endpoint to which you are sending a POST request, the request body might be of a different type, for example, it can be a JSON, plain text, XML, etc.


1. How to send a POST request in Java?

1.1. Preparing a request

String requestBody = "{\"name\": \"Example\", \"data\": {\"Attribute 1\": 123, \"Attribute 2\": \"POST Request in Java\"}}"; HttpRequest request = HttpRequest.newBuilder() .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .uri(URI.create("https://api.restful-api.dev/objects")) .header("Content-Type", "application/json") .build();


Our REST API expects a request body to be of type JSON, that's why, in the example above we created a String which represents a JSON Object. The attributes which we have created as part of a request body ("name" and "data") are not random. This particular POST endpoint recognizes the "name" attribute of type String and a "data" attribute is generic. In our case, we are passing a "data" attribute as another JSON which can have different attributes of different types but you can customize the "data" attribute type as you want, for example, it can be just a single String, Integer or float, etc.

To prepare our POST request, we are using the HttpRequest class from Java 11 version. We specify that we want to send exactly a POST request and also we provide the request body which we want to send as part of the POST request. After that, we provide the request URL of a POST request and also set up the Content-Type request header. The Content-Type header should be specified correctly because if it would not be of the same type as REST API expects it to be, the request would fail!


API Dog

1.2. Sending a request

HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body());


The HttpClient class which also comes from Java 11 version allows us to send a request. We can print our response code and response body which we would get back from a REST API.

In case if the POST request was successful, the response code would be equal to 200 and the response body from this request would look like this:

{ "id": "Some_Unique_ID", "name": "Example", "createdAt": "2023-04-15T19:14:00.129+00:00", "data": { "Attribute 1": 123, "Attribute 2": "POST Request in Java" } }


2. How to send a request body as a Java Object?

2.1. Creating an Object

In section 1.1 we have constructed the request body ourselves by manually creating a String which represents a JSON. Yes, this worked and our request was successful but how can we do it programmatically and how can we just simply take a normal Java Object and convert it to String which would represent a JSON without manually constructing anything? Let's start with the simplest things first, let's create a plain Java Object.

import java.util.HashMap; public class MyObject { private String name; private HashMap<String, Object> data; public MyObject(String name, HashMap<String, Object> data) { this.name = name; this.data = data; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, Object> getData() { return data; } public void setData(HashMap<String, Object> data) { this.data = data; } }


2.2. Jackson library

Since our REST API expects a request body to be a JSON, we will need to convert our Object to a JSON as well. To do it quickly and simply we are going to use one external library called Jackson. It is a very popular Java library that can help you to do all kinds of JSON processing in Java. However, since it is an external library, you need to add the Jackson dependency to your project's build file. For example, if you are using Maven, you can add the dependency below to your project's pom.xml file or if you are using Gradle, you can add it to your "build.gradle" file.

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.1</version> </dependency>


2.3. Object Mapper

The reason why we have imported a Jackson library is that we are going to leverage an ObjectMapper class that comes from a Jackson library. If we populate our custom Object as in the code snippet below and if we create an instance of an ObjectMapper class and call a "writeValueAsString" method from this class, it would convert our custom Java Object to a String that represents a JSON, the same as we have constructed ourselves manually in section 1.1.

HashMap<String, Object> dataAttributes = new HashMap<>(); dataAttributes.put("Attribute 1", 123); dataAttributes.put("Attribute 2", "POST Request in Java"); MyObject myObject = new MyObject("Example", dataAttributes); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(myObject);


Congratulations, now our code is more powerful and we can send POST requests using normal Java Objects!


3. Putting everything together

import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; public class Main { public static void main(String[] args) throws Exception { HashMap<String, Object> dataAttributes = new HashMap<>(); dataAttributes.put("Attribute 1", 123); dataAttributes.put("Attribute 2", "POST Request in Java"); MyObject myObject = new MyObject("Example", dataAttributes); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(myObject); HttpRequest request = HttpRequest.newBuilder() .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .uri(URI.create("https://api.restful-api.dev/objects")) .header("Content-Type", "application/json") .build(); HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); } }