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

How to Send an HTTP POST Request with JSON Data in Java?

DDD
DDDOriginal
2024-12-11 15:54:24602browse

How to Send an HTTP POST Request with JSON Data in Java?

Sending an HTTP POST Request with JSON Data in Java

If you're aiming to make an HTTP POST request while passing JSON data in Java, the following steps will guide you through the process:

1. Acquire the Apache HttpClient:
Utilize the Apache HttpClient library to enable your request.

2. Construct an HttpPost Request:
Create an HttpPost request object with the desired URL and add the "application/x-www-form-urlencoded" header.

3. Create a StringEntity for JSON:
Convert your JSON data into a StringEntity.

4. Initiate the POST Call:
Finally, execute the request using the execute() method.

Example Code:

// Import required libraries
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;

public class HttpJsonPost {

    public static void main(String[] args) {
        try {
            // Update the URL and JSON data accordingly
            String url = "http://yoururl";
            String jsonString = "{\"name\":\"xyz\",\"age\":\"20\"}";

            // Create an HTTP client
            HttpClient httpClient = HttpClientBuilder.create().build();

            // Prepare the POST request
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(jsonString);
            request.addHeader("content-type", "application/x-www-form-urlencoded");
            request.setEntity(params);

            // Execute the request
            httpClient.execute(request);
        } catch (Exception ex) {
            // Handle any exceptions
        }
    }
}

The above is the detailed content of How to Send an HTTP POST Request with JSON Data 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