Skip to content

Instantly share code, notes, and snippets.

@davidllorca
Created September 16, 2015 09:40
Show Gist options
  • Save davidllorca/aa4d18271feec98c368a to your computer and use it in GitHub Desktop.
Save davidllorca/aa4d18271feec98c368a to your computer and use it in GitHub Desktop.
Http connection with Apache client in AsyncTask
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
@Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
try {
/* create Apache HttpClient */
HttpClient httpclient = new DefaultHttpClient();
/* HttpGet Method */
HttpGet httpGet = new HttpGet(params[0]);
/* optional request header */
httpGet.setHeader("Content-Type", "application/json");
/* optional request header */
httpGet.setHeader("Accept", "application/json");
/* Make http request call */
HttpResponse httpResponse = httpclient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
/* receive response as inputStream */
inputStream = httpResponse.getEntity().getContent();
String response = convertInputStreamToString(inputStream);
parseResult(response);
result = 1; // Successful
} else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}\
@Override
protected void onPostExecute(Integer result) {
/* Download complete. Lets update UI */
if(result == 1){
arrayAdapter = new ArrayAdapter(MyActivity.this, android.R.layout.simple_list_item_1, blogTitles);
listView.setAdapter(arrayAdapter);
}else{
Log.e(TAG, "Failed to fetch data!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment