Created
October 19, 2011 08:37
-
-
Save mendhak/1297742 to your computer and use it in GitHub Desktop.
Get a URL in Java
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
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