Created
November 19, 2016 05:45
-
-
Save haydarai/3bf980f90154dd06526f1660f72d24be to your computer and use it in GitHub Desktop.
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
HttpURLConnection urlConnection = null; | |
BufferedReader reader = null; | |
String forecastJsonStr = null; | |
try { | |
String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7"; | |
String apiKey = "&APPID=" + BuildConfig.OPEN_WEATHER_MAP_API_KEY; | |
URL url = new URL(baseUrl.concat(apiKey)); | |
urlConnection = (HttpURLConnection) url.openConnection(); | |
urlConnection.setRequestMethod("GET"); | |
urlConnection.connect(); | |
InputStream inputStream = urlConnection.getInputStream(); | |
StringBuffer buffer = new StringBuffer(); | |
if (inputStream == null) { | |
return null; | |
} | |
reader = new BufferedReader(new InputStreamReader(inputStream)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
buffer.append(line + "\n"); | |
} | |
if (buffer.length() == 0) { | |
return null; | |
} | |
forecastJsonStr = buffer.toString(); | |
} catch (IOException e) { | |
Log.e("MainActivityFragment", "Error ", e); | |
return null; | |
} finally{ | |
if (urlConnection != null) { | |
urlConnection.disconnect(); | |
} | |
if (reader != null) { | |
try { | |
reader.close(); | |
} catch (final IOException e) { | |
Log.e("MainActivityFragment", "Error closing stream", e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment