Apache HTTPClient Post Request with Jackson Object mapper


To use Apache HttpClient with Jackson’s Object Mapper for handling JSON serialization and deserialization, you can follow these steps:

  • Add the necessary dependencies to your project. You will need both the Apache HttpClient library and the Jackson library. Here’s an example of the dependencies you can include in your build file (Maven):
<dependencies>
    <!-- Apache HttpClient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>

    <!-- Jackson Core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.13.0</version>
    </dependency>
    <!-- Jackson Data Bind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.0</version>
    </dependency>
</dependencies>
  • Create an instance of HttpClient using HttpClientBuilder.
  • Create an instance of HttpPost with the target URL.
  • Prepare your request payload as a Java object.
  • Use Jackson’s ObjectMapper to serialize the Java object into JSON. You can convert the serialized JSON to a string.
  • Set the request entity as a StringEntity with the serialized JSON payload and content type set to application/json.
  • Execute the request using httpClient.execute(httpPost).
  • Handle the response as needed.

HttpClient with Jackson FasterXML example

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class ApacheHttpClientWithJacksonExample {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClientBuilder.create().build();

        try {
            // Specify the URL endpoint for the POST request
            HttpPost httpPost = new HttpPost("http://example.com/api/resource");

            // Prepare your request payload as a Java object
            RequestPayload payload = new RequestPayload();
            payload.setName("John");
            payload.setAge(30);

            // Use Jackson's ObjectMapper to serialize the Java object to JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(payload);

            // Set the request entity as a StringEntity with the serialized JSON payload
            StringEntity stringEntity = new StringEntity(requestBody);
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);

            // Execute the request
            HttpResponse response = httpClient.execute(httpPost);

            // Get the response status code
            int statusCode = response.getStatusLine().getStatusCode();

            // Get the response body
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);

            // Close the response entity
            EntityUtils.consume(responseEntity);

            // Handle the response
            System.out.println("Response Code: " + statusCode);
            System.out.println("Response Body: " + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the HttpClient instance
            httpClient.getConnectionManager().shutdown();
        }
    }

    // Example RequestPayload class
    static class RequestPayload {
        private String name;
        private int age;

        // getters and setters

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

In this example, we use Jackson’s ObjectMapper to serialize the RequestPayload Java object into a JSON string. We set the serialized JSON as the request entity using StringEntity and set the content type to application/json.

You can customize the RequestPayload class as needed to match your JSON structure. Make sure to include the necessary getters and setters for the object properties.

Please ensure that you have the Apache HttpClient and Jackson libraries added to your project dependencies before running the code.