Skip to content

Instantly share code, notes, and snippets.

@mendhak
Created October 19, 2011 08:37
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 mendhak/1297742 to your computer and use it in GitHub Desktop.
Save mendhak/1297742 to your computer and use it in GitHub Desktop.
Get a URL in Java
public static String GetUrl(String url) throws Exception
{
URL serverAddress = null;
HttpURLConnection connection = null;
// OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try
{
serverAddress = new URL(url);
// set up out communications stuff
connection = null;
// Set up the initial connection
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.setConnectTimeout(10000);
connection.connect();
// read the result from the server
rd = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
return sb.toString();
}
catch (Exception e)
{
throw e;
// Swallow
}
finally
{
// close the connection, set all objects
// to null
connection.disconnect();
rd = null;
sb = null;
// wr = null;
connection = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment