Skip to content

Instantly share code, notes, and snippets.

@marosc
Created October 17, 2016 09:27
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 marosc/c01e8fd4f490d395f4577db1f7531bde to your computer and use it in GitHub Desktop.
Save marosc/c01e8fd4f490d395f4577db1f7531bde to your computer and use it in GitHub Desktop.
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw response as a string.
String response = null;
try {
// Construct the URL for query
String baseUrl = "http://wwww.mcomputing.eu";
URL url = new URL(baseUrl);
// Create the request, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's HTML, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty.
return null;
}
response = buffer.toString();
} catch (IOException e) {
// we didn't successfully get the data
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
//handle exception
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment