Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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);
}
}
}
@AlexKorovyansky

This comment has been minimized.

Copy link

@AlexKorovyansky AlexKorovyansky commented Jul 27, 2014

why .txt, not .java?

@akmalabbasov

This comment has been minimized.

Copy link

@akmalabbasov akmalabbasov commented Jul 28, 2014

Hi, what is the purpose of using StringBuffer instead of StringBuilder? Thank you!

@gier3k

This comment has been minimized.

Copy link

@gier3k gier3k commented Jul 29, 2014

@korovyansk - it is just snipet, part of code, not even full method

@marceloguedes

This comment has been minimized.

Copy link

@marceloguedes marceloguedes commented Aug 7, 2014

This excerpt should have an "else" keyword, right?

    if (buffer.length() == 0) {
        // Stream was empty.  No point in parsing.
        forecastJsonStr = null;
    }
    forecastJsonStr = buffer.toString();
@briansudo

This comment has been minimized.

Copy link

@briansudo briansudo commented Aug 7, 2014

@marceloguedes buffer.toString() will return "" if nothing has been appended. And, we don't want forecastJsonStr to be null.

@dagansandler

This comment has been minimized.

Copy link

@dagansandler dagansandler commented Aug 8, 2014

@briansudev Then why do we set it to null inside that "if" statement?

Also, this seems rather pointless:

if (inputStream == null) {
    // Nothing to do.
    forecastJsonStr = null;
}

forecastJsonStr is already null at that point (and can't be anything else) and we go on to simply using the input stream anyway, so why bother to do this check? It may be there as a placeholder to build on, but still pretty useless at this point.

@KamilLelonek

This comment has been minimized.

Copy link

@KamilLelonek KamilLelonek commented Aug 9, 2014

@benWoz

This comment has been minimized.

Copy link

@benWoz benWoz commented Aug 13, 2014

@KamilLelonek you've got a bug in your code trying to instantiate Httpconnection when it should be HttpURLConnection. That was unfortunate.

@ewoks

This comment has been minimized.

Copy link

@ewoks ewoks commented Aug 16, 2014

there are more bugs in his code, cause it can't compile..

@AlexKorovyansky

This comment has been minimized.

Copy link

@AlexKorovyansky AlexKorovyansky commented Sep 13, 2014

@gier3k in case of .java it will be highlighted as java code, and will be much easy to read :)

@dsteb

This comment has been minimized.

Copy link

@dsteb dsteb commented Oct 12, 2014

Join to others.

  1. The language of the code here is not text, it's Java. Enable code higlighting, please.
  2. if (inputStream == null) {
    // Nothing to do.
    forecastJsonStr = null;
    }
    on line 23. It is useless, forecastJsonStr is null, if you mean return null here, it's better to write it.
  3. The same on line 37, forecastJsonStr can't be not null. Why don't you write return, if you mean return?
    if (buffer.length() == 0) {
    // Stream was empty. No point in parsing.
    forecastJsonStr = null;
    }
  4. I think, synchronized StringBuffer is useless here, we should use StringBuilder.
    @gier3k the language of snippet is Java, it's not plain text snippet.
@Jazzeroki

This comment has been minimized.

Copy link

@Jazzeroki Jazzeroki commented Oct 15, 2014

In regards to StringBuffer vs StringBuilder, StringBuffer is a syncronized thread safe class however, since it's threaded suprisingly it runs slower than StringBuilder. So unless you are using threads on the data it's faster to use StringBuilder. In the end though both will work just the same as the other.

@yjaeseok

This comment has been minimized.

Copy link

@yjaeseok yjaeseok commented Jan 23, 2015

Why don't you change format .txt to .java for highlight syntax?

@yaix

This comment has been minimized.

Copy link

@yaix yaix commented Feb 7, 2015

Has anybody a hint why the repeated

forecastJsonStr = null;

is for? I am new to Java, but these seem totally useless, because it has already that value.

@jjmcgaffey

This comment has been minimized.

Copy link

@jjmcgaffey jjmcgaffey commented Feb 13, 2015

It's protection. Yes, forecastJsonStr is supposed to be null at this point - there's nothing in the code (so far) that will make it not null. But you can get some truly weird and undetectable bugs by assuming that a string that should be null is null. It's a heck of a lot safer to explicitly set it null.
If you were writing for a Timex-Sinclair or a 2001 smartphone (2K-64K memory), it might be worth leaving it out to save a line or two of code. We've got the room, now, to write for safety - and the person who works on your code after you will be MUCH happier if you do.

@idesignedme

This comment has been minimized.

Copy link

@idesignedme idesignedme commented Mar 23, 2015

why in the world do we live in, is there so much outdated code in tutorials? it takes a second to get an ambitious intern to make a video that is completely up to date. These tutorials suck

@imcalledsee

This comment has been minimized.

Copy link

@imcalledsee imcalledsee commented Aug 19, 2015

I did a network-snippet myself as this looked pretty bad. The only thing the code above does is fetching some json from a website. So why don't just use a external method that can be reused for it?`-

public String getPageSource(String pageUrl)
{
    StringBuffer buffer = new StringBuffer();

    try
    {
        URL url = new URL(pageUrl);
        InputStream is = url.openStream();
        int pointer = 0;
        while ((pointer = is.read()) != -1) 
        {
            buffer.append((char)ptr);
        }
    } catch (Exception e) {e.printStackTrace();}

    return buffer.toString();
}

Have fun with it :)

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Nov 26, 2015

So it's safe to use StringBuilder instead of StringBuffer as threads are not in play here?

@biniama

This comment has been minimized.

Copy link

@biniama biniama commented Dec 23, 2015

In the following code, the MyOpenWeatherMapApiKey you got from OWM should be wrapped in single quote and then double quote for the app to run (at least in my case)

buildTypes.each {
    it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', ' "MyOpenWeatherMapApiKey" '
}
@spnote

This comment has been minimized.

Copy link

@spnote spnote commented Jan 16, 2016

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

@Andlearn

This comment has been minimized.

Copy link

@Andlearn Andlearn commented Feb 6, 2016

@biniama Thanks! You saved me the trouble.

@bkmagnetron

This comment has been minimized.

Copy link

@bkmagnetron bkmagnetron commented Mar 2, 2016

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

This comment has been minimized.

Copy link

@wahidnurhani wahidnurhani commented Mar 6, 2016

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

This comment has been minimized.

Copy link

@dschiffers dschiffers commented Mar 16, 2016

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

@ghost

This comment has been minimized.

Copy link

@ghost 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

This comment has been minimized.

Copy link

@randypfohl randypfohl commented Aug 25, 2016

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

This comment has been minimized.

Copy link

@azdafirmansyah azdafirmansyah commented Sep 15, 2016

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

@VaibhavAWD

This comment has been minimized.

Copy link

@VaibhavAWD 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

This comment has been minimized.

Copy link

@VaibhavAWD VaibhavAWD commented Oct 1, 2016

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

This comment has been minimized.

Copy link

@VaibhavAWD VaibhavAWD commented Oct 1, 2016

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

This comment has been minimized.

Copy link

@rmohan80 rmohan80 commented Oct 3, 2016

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

@chasen-bettinger

This comment has been minimized.

Copy link

@chasen-bettinger chasen-bettinger commented Jan 15, 2017

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
You can’t perform that action at this time.