Skip to content

Instantly share code, notes, and snippets.

@haydarai
Created November 19, 2016 05:45
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 haydarai/3bf980f90154dd06526f1660f72d24be to your computer and use it in GitHub Desktop.
Save haydarai/3bf980f90154dd06526f1660f72d24be to your computer and use it in GitHub Desktop.
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