Created
September 16, 2015 09:40
-
-
Save davidllorca/aa4d18271feec98c368a to your computer and use it in GitHub Desktop.
Http connection with Apache client in AsyncTask
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
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