Skip to content

Instantly share code, notes, and snippets.

@jonnybest
Created December 6, 2013 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonnybest/7826243 to your computer and use it in GitHub Desktop.
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.
/** 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