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();
}
}
HTTPUtility
Class
public class HTTPAsyncTask extends AsyncTask<String, Void, String>HttpUtility {
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, JSONObjectstatic jsonObj,String GET(String requesturl) {
mCb = c;
mTypeOfRequest = request;
mJSONPostData = jsonObj;
InputStream if((datainputStream != null) && (jsonObj == null)){null;
String mDataresult = data;"";
try if(mTypeOfRequest.equalsIgnoreCase("GET")){
Iterator<String> it = mData.keySet().iterator();
// create while(it.hasNext()){HttpClient
StringHttpClient keyhttpclient = it.next();
mParams.add(new BasicNameValuePair(key, mData.getDefaultHttpClient(key)));
}
// formake (intGET irequest =to 0;the i<mParams.size()-1;given i++){URL
mStrToBeAppended+=HttpResponse "?"httpResponse += mParams.get(i)httpclient.getNameexecute() + "=" +new mParams.getHttpGet(iurl).getValue() + "&"; ;
}
//add the last parameterreceive withoutresponse theas "&"inputStream
mStrToBeAppended+= "?" + mParams.get(mParams.size()-1).getName() + "="inputStream += mParams.get(mParamshttpResponse.sizegetEntity()-1).getValuegetContent();
}
// convert inputstream to string
if(mTypeOfRequest.equalsIgnoreCase("POST")){
Iterator<String> itinputStream != mData.keySet().iterator();
while(it.hasNext()null){
String keyresult = it.nextconvertInputStreamToString(inputStream);
mParams.add(new BasicNameValuePair(key, mData//inputStream.getclose(key)));
}
}
} else
if ((mData == null) && (jsonObj ! result = null)"Did not work!";
} catch (Exception e) {
isPostDataInJSONFormat =Log.d("InputStream", true;e.getLocalizedMessage());
}
return result;
}
@Override
public protectedstatic String doInBackgroundPOST(String... baseUrls)url, List<NameValuePair> mParams){
InputStream inputStream = null;
publishProgress(null);String result = "";
if(mTypeOfRequest.equalsIgnoreCase("GET"))try{
StringHttpClient finalURLhttpclient = baseUrls[0]+new mStrToBeAppended;DefaultHttpClient();
HttpPost returnpost HttpUtility.GET= new HttpPost(finalURLurl);
}
post.setEntity(new UrlEncodedFormEntity(mParams, "UTF-8"));
HttpResponse httpResponse if= (mTypeOfRequesthttpclient.equalsIgnoreCaseexecute("POST")post){;
if(isPostDataInJSONFormat
== false){
// receive response as inputStream
return HttpUtility inputStream = httpResponse.POSTgetEntity(baseUrls[0],mParams ).getContent();
} // convert inputstream to string
elseif(inputStream != null){
returnresult HttpUtility.POST= convertInputStreamToString(baseUrls[0],inputStream);
mJSONPostData //inputStream.close();
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protectedpublic voidstatic onPostExecute(String result) {
mCb.onResult(result);
}
@Override
protected void onProgressUpdatePOST(Void...voids ) {
String url, JSONObject mCb.onProgress(obj);
}
}
**`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 StringHttpClient POST(Stringhttpclient url,= List<NameValuePair>new mParamsDefaultHttpClient(){
InputStream inputStream = null;;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntitysetHeader(mParams, "UTF"Content-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"type", e.getLocalizedMessage()"application/json");
}
return result;
} StringEntity se = new StringEntity(obj.toString());
public static String POST se.setContentEncoding(Stringnew urlBasicHeader(HTTP.CONTENT_TYPE, JSONObject"application/json"));
obj post.setEntity(se){;
InputStream inputStream = null;
StringHttpResponse resulthttpResponse = "";httpclient.execute(post);
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));else
String line = "";
String result = "";
while((line ="Did bufferedReader.readLine())not work!= null)";
} catch result(Exception +=e) line;{
Log.d("InputStream", inputStreame.closegetLocalizedMessage());
return result;
}
return result;
}
**`Callback interface`** 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;
}
}
Callback
interface
public interface CallBack {
public void onProgress();
public void onResult(String result);
public void onCancel();
}
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 interfacevoid CallBackonResult(String result) {
public// voidTODO onProgressAuto-generated method stub
mProgressDialog.dismiss();
public voidmStrResult onResult(String= result);result;
publicToast.makeText(getApplicationContext(), voidmStrResult, onCancelToast.LENGTH_SHORT).show();
}
**Main Activity Class** @Override
**Inside the Activity class** public void onCancel() {
// TODO Auto-generated method stub
}
};
And then the Asynctask is called inside the Activity like the following:
//For JSON Postdata
String url= "Your URL"
final CallBackJSONObject cpostData = 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 onCancelJSONObject() {
// TODO Auto-generated method stub
}
};
**And then the Asynctask is called inside the Activity like the following:**
//For JSON Postdata
String url= "Your URL"
JSONObject postData = new JSONObject();
postData.put(Key1, Data1);
postData.put(Key2, Data2);
HTTPAsyncTask asyncTask = new AsyncTask(mContext,mCallback, null, postData, "POST");
asyncTask.execute(url);
//For Get data
String url = "Your URL";
HashMap getData = new HashMap<Object, Object>();
getData.put("Key",Data);
getData.put("Key",Data));
mGetGCMMessageAsyncTask = new HTTPAsyncTask(mContext, mCallback, getData, null, "GET");
mGetGCMMessageAsyncTask.execute(url);