Networking with java.net.URL and java.net.HttpURLConnection in Java


Use URL and HttpURLConnection for basic HTTP requests, allowing for both retrieval and submission of web content.

Source Code

URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

System.out.println(response.toString());
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments