HTTP POST using JSON in Java
To make an HTTP POST request using JSON in Java, you can use the HttpURLConnection class available in the java.net package. Here's an example of how to do it:
To make an HTTP POST request using JSON in Java, you can use the HttpURLConnection class available in the java.net package. Here's an example of how to do it:
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api/v1/create";
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(json.getBytes(StandardCharsets.UTF_8));
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
java.io.InputStream inputStream = responseCode >= 200 && responseCode < 300 ? con.getInputStream() : con.getErrorStream();
try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream != null ? inputStream : new ByteArrayInputStream(new byte[0]), StandardCharsets.UTF_8))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response.toString());
}
}
}In this example, the HttpURLConnection object is used to send an HTTP POST request to the specified URL with the JSON data in the request body. The Content-Type header is set to application/json to indicate that the request payload contains JSON. The code also explicitly specifies UTF-8 encoding for both the request body and the response stream, and safely selects the appropriate input stream based on the HTTP response code. For production applications, consider using established third-party libraries like OkHttp or Apache HttpClient, which handle connection pooling, retries, and resource management more robustly.