I have developed a generic HTTP functionality using Android Asynctask and Apache HTTP client. Please review the code and let me know if it is the right way of doing or there are other ways to achieve it.
The Async Class
public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
private CallBack mCb;
HashMap<String, String> mData = null;
List<NameValuePair> mParams= new ArrayList<NameValuePair>();
String mTypeOfRequest;
String mStrToBeAppended = "";
boolean isPostDataInJSONFormat = false;
JSONObject mJSONPostData = null;
public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj, String request) {
mCb = c;
mTypeOfRequest = request;
mJSONPostData = jsonObj;
if((data != null) && (jsonObj == null)){
mData = data;
if(mTypeOfRequest.equalsIgnoreCase("GET")){
Iterator<String> it = mData.keySet().iterator();
while(it.hasNext()){
String key = it.next();
mParams.add(new BasicNameValuePair(key, mData.get(key)));
}
for (int i = 0; i<mParams.size()-1; i++){
mStrToBeAppended+= "?" + mParams.get(i).getName() + "=" + mParams.get(i).getValue() + "&";
}
//add the last parameter without the "&"
mStrToBeAppended+= "?" + mParams.get(mParams.size()-1).getName() + "=" + mParams.get(mParams.size()-1).getValue();
}
if(mTypeOfRequest.equalsIgnoreCase("POST")){
Iterator<String> it = mData.keySet().iterator();
while(it.hasNext()){
String key = it.next();
mParams.add(new BasicNameValuePair(key, mData.get(key)));
}
}
}
if ((mData == null) && (jsonObj != null)){
isPostDataInJSONFormat = true;
}
}
@Override
protected String doInBackground(String... baseUrls) {
publishProgress(null);
if(mTypeOfRequest.equalsIgnoreCase("GET")){
String finalURL = baseUrls[0]+ mStrToBeAppended;
return HttpUtility.GET(finalURL);
}
if (mTypeOfRequest.equalsIgnoreCase("POST")){
if(isPostDataInJSONFormat == false){
return HttpUtility.POST(baseUrls[0],mParams );
}
else {
return HttpUtility.POST(baseUrls[0], mJSONPostData);
}
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
mCb.onResult(result);
}
@Override
protected void onProgressUpdate(Void...voids ) {
mCb.onProgress();
}
}
The HTTPUtility Class
public class HttpUtility {
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
//inputStream.close();
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
public static String POST(String url, List<NameValuePair> mParams){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(mParams, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(post);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
//inputStream.close();
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
public static String POST(String url, JSONObject obj){
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse httpResponse = httpclient.execute(post);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
The Callback interface
public interface CallBack {
public void onProgress();
public void onResult(String result);
public void onCancel();
}
The Main Activity Class Inside the Activity class
final CallBack c = new CallBack(){
@Override
public void onProgress() {
// TODO Auto-generated method stub
mProgressDialog.show();
}
@Override
public void onResult(String result) {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
mStrResult = result;
Toast.makeText(getApplicationContext(), mStrResult, Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
// TODO Auto-generated method stub
}
};
And then the Asynctask is called inside the Activity like the following
//testing GET without parameters....
String url = "http://hmkcode.appspot.com/rest/controller/get.json";
mHttpAsyncTaskGET = new HTTPAsyncTask(c, null,null "GET");
mHttpAsyncTaskGET.execute(url);
//testing GET with parameters
//testing POST with data
String url= "https://selfsolve.apple.com/wcResults.do";
mData.put("sn", "C02G8416DRJM");
mData.put("cn", "");
mData.put("locale", "");
mData.put("caller", "");
mData.put("num", "12345");
mHttpAsyncTaskPOST = new HTTPAsyncTask(c, mData,null, "POST");
mHttpAsyncTaskPOST.execute(url);