Appearance
How to use java.net.URLConnection to fire and handle HTTP requests
You can use the java.net.HttpURLConnection class to fire and handle HTTP requests in Java. Here's an example of how you can use it to send a GET request and read the response:
java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}This code sends a GET request to the specified URL and prints the response to the console.
You can also use HttpURLConnection to send other HTTP methods, such as POST, PUT, or DELETE, by calling setRequestMethod and writing data to the output stream via getOutputStream.
I hope this helps! Let me know if you have any other questions.