Skip to content

Instantly share code, notes, and snippets.

Created May 27, 2014 19:42
Show Gist options
  • Select an option

  • Save anonymous/6b306e1f6a21b3718fa4 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/6b306e1f6a21b3718fa4 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 JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, 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.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, 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. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
forecastJsonStr = null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
@wonook
Copy link

wonook commented Oct 31, 2014

Great!
Thanks!

@frankkienl
Copy link

Why not use the Apache HTTP library?

@mcka1n
Copy link

mcka1n commented Nov 17, 2014

@frankkienl They recommended the HttpURLConnection class because it's a general implementation and lightweight.

@jahlomp
Copy link

jahlomp commented Dec 4, 2014

great

@amoltandel
Copy link

Love that piece of code! It can't be more simplified! :)

@raincrash
Copy link

Thanks for the clean code.

@tonmoy71
Copy link

Code is poetry!

Copy link

ghost commented Dec 28, 2014

Beautiful and clean code

Copy link

ghost commented Jan 14, 2015

good

@sbmaggarwal
Copy link

Can't be better!

@hoanganh200870
Copy link

I think we can use HttpGet to get simply code

String url = "http://api.openweathermap.org/data/2.5/forecast/daily?cnt=7&q=94043&mode=json&units=metric";
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
try {
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String data = EntityUtils.toString(entity);
    Log.e("Data", data);
} catch (IOException e) {
    e.printStackTrace();
}

@bigsony
Copy link

bigsony commented Jan 22, 2015

Great, I like it.

@billbonney
Copy link

Lines 25, 39, 46 all assign null to forecastJsonStr which will always be null at those points, since it is only assigned to a value as the last line of the try block line 41 with the toString which doesn't create an exception.

The catch block needs only print the error message, the assignment of forecastJsonStr to null is unnecessary as well.

@hoanganh200870 your solution looks tidy 👍

@patcon
Copy link

patcon commented Feb 10, 2015

This person forked and changed to java filetype for syntax highlighting:
https://gist.github.com/yeow/60adb201fa866aff8503

@gwadya
Copy link

gwadya commented Feb 27, 2015

where to place this code

@maram2012
Copy link

I need the second gist for android setting
i coudnt found the link ?!!!

@ShehryarShaukat
Copy link

Its all starting to make some sense now :P

@aogaga
Copy link

aogaga commented Mar 22, 2015

good.

@mridulhaze
Copy link

nice

@masterpradipg
Copy link

Cannot be more simpler than this....

@MOHS3N
Copy link

MOHS3N commented Jun 13, 2015

GOOD , 😃
دمتان گرم ، آبادمان کردید 😊

@praveenj-github
Copy link

Good :-)
Thank You...

@saisumit
Copy link

saisumit commented Sep 4, 2015

thanku developer.google for such a great code

@Mostafa-Rady
Copy link

Retrofit is more better

@Arashghabussi
Copy link

havnt any errors. i love it

@mawohry
Copy link

mawohry commented Dec 5, 2015

great

@RajuKoushik
Copy link

Great !!

@maudmcok
Copy link

I like Super Clean 👍 💯

@Soroush-aali-bagi
Copy link

مرسی گوگول 👍

@habibfahad
Copy link

error: unreachable statement
.
.
.
at this
HttpURLConnection urlConnection = null;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment