Created
November 9, 2015 16:36
-
-
Save dastergon/00302cfd58ed161f318e to your computer and use it in GitHub Desktop.
HTTP GET request in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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