In Java, you can handle URLs and establish HTTP connections using the java.net package, specifically the URL and HttpURLConnection classes. Here’s an example of how you can work with URLs and establish an HTTP connection:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("https://api.example.com/data");
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method (GET, POST, etc.)
connection.setRequestMethod("GET");
// Set other optional properties, such as headers
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// Get the response code
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Print the response
System.out.println("Response: " + response.toString());
// Disconnect the connection
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a URL object with the desired URL. We then cast the URLConnection returned by url.openConnection() to HttpURLConnection. We can set properties on the connection, such as the request method (GET, POST, etc.) and headers. After establishing the connection, we can retrieve the response code using getResponseCode() and read the response using a BufferedReader. Finally, we disconnect the connection.
Note that this is a basic example, and you may need to handle exceptions, handle different response codes, and work with request and response bodies depending on your specific requirements.




