Home >Java >javaTutorial >How to Make an HTTP POST Request with JSON in Java?

How to Make an HTTP POST Request with JSON in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 03:51:15691browse

How to Make an HTTP POST Request with JSON in Java?

Make an HTTP POST Request with JSON in Java

HTTP POST requests are often used to send data to a server. This article demonstrates how to create an HTTP POST request in Java using JSON.

Apache HttpClient Setup

To make HTTP requests, we'll utilize the Apache HttpClient. First, add the dependency to your project:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

Creating the POST Request

HttpPost request = new HttpPost("http://www.site.com"); // Replace with your URL

Adding JSON Body

String json = "{\"name\":\"myname\",\"age\":\"20\"}";
StringEntity params = new StringEntity(json);
params.setContentType("application/json");
request.setEntity(params);

Processing the Request

HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(request);

Handling the Response

Depending on your application logic, you can parse the response to extract the relevant data.

Lack of POST Method in JSON

The JSON API doesn't define a dedicated POST method since it provides a representation of data, not a mechanism for making requests.

The above is the detailed content of How to Make an HTTP POST Request with JSON in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn