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
Release: 2024-12-09 03:51:15
Original
678 people have browsed it

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>
Copy after login

Creating the POST Request

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

Adding JSON Body

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

Processing the Request

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template