Skip to content

Instantly share code, notes, and snippets.

@betandr
Created July 21, 2014 17:41
Show Gist options
  • Save betandr/7235cd9882b7539a23cd to your computer and use it in GitHub Desktop.
Save betandr/7235cd9882b7539a23cd to your computer and use it in GitHub Desktop.
private class DownloadJsonTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... strings) {
JSONObject jsonObject = null;
try {
InputStream is = new URL(strings[0].toString()).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
jsonObject = new JSONObject(readAll(rd));
} finally {
is.close();
}
} catch (Exception e) {
Log.e("DownloadJsonTask", e.getMessage());
}
return jsonObject;
}
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
}
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
@roberton
Copy link

Cool, works really well. Thanks :-)

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