Created
March 14, 2013 07:08
-
-
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
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
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