Skip to content

Instantly share code, notes, and snippets.

Created July 22, 2014 00:51
Show Gist options
  • Star 63 You must be signed in to star a gist
  • Fork 77 You must be signed in to fork a gist
  • Save anonymous/1c04bf2423579e9d2dcd to your computer and use it in GitHub Desktop.
Save anonymous/1c04bf2423579e9d2dcd 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 available 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 attempting
// 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);
}
}
}
@spnote
Copy link

spnote commented Jan 16, 2016

@biniama Thanks for your help.
My environment: Mac, Android Studio 1.5

@Andlearn
Copy link

Andlearn commented Feb 6, 2016

@biniama Thanks! You saved me the trouble.

@balakrishnangithub
Copy link

This is my understanding of this code snippet,

Task
We have to send a HTTP request to an URL and GET some data.

Solving

  • Create a new variable for the URL
    new URL(...)
  • Use the URL to create and open HttpURLConnection
    openConnection()
  • Now send a GET request
    setRequestMethod("GET")
  • If we get response for our request
    inputStream != null
    buffer the data and store it as a String.
    new BufferedReader()
  • And "finally" close the HttpURLConnection
    disconnect()

@wahidnurhani
Copy link

i still don't understand why ->

// 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;

can someone tell me why can't I close that if I put them inside try block?

@dschiffers
Copy link

it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', ""xxxxxxxxxxxxxxxxxx""

Copy link

ghost commented Apr 27, 2016

@wahidnurhani because in that case these variables will be in the inner score of the try block and not visible in the finally block.

@randypfohl
Copy link

Guys, Please understand this is a code snippet

this is not a valid java file

Hence, why it's not in .java...Not to be rude but if you need it in .java you are more than capable.

@azdafirmansyah
Copy link

agree with @randypfofl, this is just code snippet. you can change everything with your coding style.

@VaibhavAWD
Copy link

VaibhavAWD commented Oct 1, 2016

I did not received any error on my end. I then tried running the URL and found invalid API Key as follows,

{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}

Please help me on this.

@VaibhavAWD
Copy link

I found the solution by myself... It is just because the Open Weather Map has updated their portal saying that they have made few things secure due to which you will have to generate registered API Key. I used mine and now its working fine!

@VaibhavAWD
Copy link

But when I am trying to use the URL in the app the is still not showing any error. The App continues to work fine... Strange!

@rmohan80
Copy link

rmohan80 commented Oct 3, 2016

@VaibhavAWD well, it still crashes for me. Maybe you're adding it in the wrong location?

@chasen-bettinger
Copy link

I wrote the network call using the Ion library.

Ion.with(this)
                    .load(baseURL.concat(api_key))
                    .asString()
                    .setCallback(new FutureCallback<String>() {
                        @Override
                        public void onCompleted(Exception e, String result) {
                            if(result != null) {
                                logResult(result);
                            }

                        }
                    });

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