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:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
String url = "http://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);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
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