How to send HTTP request in Java?
In Java, you can send an HTTP request using the java.net.URL
and java.net.HttpURLConnection
classes.
Here is an example of how to send an HTTP GET request and print the response:
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream())
);
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(status);
System.out.println(content);
}
}
This example sends an HTTP GET request to the specified URL and prints the HTTP status code and the response body.
To send an HTTP POST request, you can use the setDoOutput(true)
method and write the request body to the OutputStream
returned by the getOutputStream()
method.
Here is an example of how to send an HTTP POST request with a JSON payload:
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json");
String jsonInputString = "{\"name\": \"John\", \"age\": 30}";
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int status = con.getResponseCode();
BufferedReader in = new Buff