In this example, we will use basic HttpURLConnection Object to post json object.
Java HttpURLConnection Post Request:
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { public static void main(String[] args) { try { // Specify the URL endpoint for the POST request URL url = new URL("https://example.com/api/resource"); // Create the HttpURLConnection object HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set the request method to POST connection.setRequestMethod("POST"); // Enable input and output streams connection.setDoInput(true); connection.setDoOutput(true); // Set the content type for the request connection.setRequestProperty("Content-Type", "application/json"); // Create the request body String requestBody = "{\"name\":\"John\", \"age\":30}"; // Write the request body to the output stream DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(requestBody); outputStream.flush(); outputStream.close(); // Get the response code int responseCode = connection.getResponseCode(); // Read the response from the input stream BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } // Close the reader and connection reader.close(); connection.disconnect(); // Handle the response System.out.println("Response Code: " + responseCode); System.out.println("Response Body: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } }
In this example, we create a HttpURLConnection
object and set the request method to POST. We enable input and output streams to read the response and write the request body, respectively. We also set the Content-Type
header to specify that the request body is in JSON format.
We then write the request body to the output stream, flush and close the stream. Next, we retrieve the response code and read the response from the input stream. Finally, we close the reader and the connection.
Please note that the example assumes the endpoint accepts JSON data. You may need to modify the code accordingly if your use case requires a different content type or request body format.
Thanks for Reading…
Read below post for Apache HttpClient Post Request:
https://www.javasavvy.com/post-json-request-using-apache-httpclient/