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!