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!