Created
December 6, 2013 15:12
-
-
Save jonnybest/7826243 to your computer and use it in GitHub Desktop.
This is a simple method for fetching web content. It's my fork of http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139 which is for POST requests only.
This file contains 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
/** Fetches a website from the given URL. | |
* | |
* @param targetURL | |
* @return the website as a string | |
* @throws IOException | |
*/ | |
public static String executeGet(String targetURL) throws IOException { | |
URL url; | |
HttpURLConnection connection = null; | |
// Create connection | |
url = new URL(targetURL); | |
connection = (HttpURLConnection) url.openConnection(); | |
connection.setRequestMethod("GET"); | |
// configure socket settings | |
connection.setUseCaches(false); | |
connection.setDoInput(true); | |
connection.setReadTimeout(15000); // wait 15 seconds | |
//System.out.println("connection prepared. now sending"); | |
// Send & Get Response | |
InputStream is = connection.getInputStream(); | |
BufferedReader rd = new BufferedReader(new InputStreamReader(is)); | |
String line; | |
StringBuffer response = new StringBuffer(); | |
while ((line = rd.readLine()) != null) { | |
response.append(line); | |
response.append('\r'); | |
} | |
connection.disconnect(); | |
rd.close(); | |
return response.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment