Skip to content

Instantly share code, notes, and snippets.

@dastergon
Created November 9, 2015 16:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dastergon/00302cfd58ed161f318e to your computer and use it in GitHub Desktop.
Save dastergon/00302cfd58ed161f318e to your computer and use it in GitHub Desktop.
HTTP GET request in Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLCon {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLCon http = new HttpURLCon();
System.out.println("Sending HTTP GET request");
http.sendGet();
}
private void sendGet() throws Exception {
String url = "https://example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//Request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment