Skip to content

Instantly share code, notes, and snippets.

@oozman
Created March 14, 2013 07:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oozman/5159426 to your computer and use it in GitHub Desktop.
Save oozman/5159426 to your computer and use it in GitHub Desktop.
Getting data from API URL using GET in Android (AsyncTask). Credits: http://goo.gl/5hgFC
private class LongRunningGetIO extends AsyncTask <Void, Void, String>{
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException{
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0){
out.append(new String(b, 0, n));
}
}
return out.toString();
}
@Override
protected String doInBackground(Void... params){
HttpClient httpClient = new DefaultHttpClient() ;
HttpContext localContext = new BasicHttpContext();
String resource_url = "http://api.example.com/resource";
HttpGet httpGet = new HttpGet(resource_url);
//Add user authentication
String username = "USERNAME HERE";
String password = "PASSWORD HERE";
httpGet.addHeader("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(),Base64.NO_WRAP));
String text = null;
try{
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e){
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results){
if (results!=null){
//Add some actions here if successful
Log.d("RESULT", results);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment