Skip to main content
Rollback to Revision 13
Source Link
Phrancis
  • 20.4k
  • 6
  • 68
  • 154
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    private CallBack mCb; 
    LinkedHashMap<Object, Object> mData = null;
    //List mParams= newprivate ArrayList();CallBack mCb;
    LinkedHashMap<ObjectHashMap<String, Object>String> mParamsmData = new LinkedHashMap<>();null;
    List<NameValuePair> mPostDataList =mParams= new ArrayList<>ArrayList<NameValuePair>();
    String mTypeOfRequest; 
    String mStrToBeAppended = "?";"";
    boolean isPostDataInJSONFormat = false;
    boolean JSonAndData = false;
    //JSONObject mJSONPostData = null;
    String JSONStringData = null;
    Context mContext = null;
    
    public HTTPAsyncTask(Context context, CallBack c, HashMap<ObjectHashMap<String, Object>String> data, StringJSONObject jsonStringjsonObj, String request) {
        mContext = context;
        mCb = c;
        mTypeOfRequest = request;
        JSONStringDatamJSONPostData = jsonString;
        //Log.i("JSONDATA", mJSONPostData.toString());jsonObj;
        if((data != null) && (jsonStringjsonObj == null)){
            mData = (LinkedHashMap)data;
            if(mTypeOfRequest.equalsIgnoreCase("GET")){
            Object key = null;
            Iterator<Object>Iterator<String> it = mData.keySet().iterator();
                while(it.hasNext()){ 
                    String key = it.next(); 
                mParams.put(key, mData.get(key));
                LogmParams.dadd("Data",new key.toStringBasicNameValuePair() + " " +key, mData.get(key).toString());
                }
            Iterator<Object>itParams = mParams.keySet().iterator();
           for (int sizeOfParamsi = mParams0; i<mParams.size();
 -1; i++){
          int index = 0;
         mStrToBeAppended+= "?" + while(itParamsmParams.hasNextget(i).getName(){
                Object+ keyParams"=" =+ itParamsmParams.nextget(i);
 .getValue() + "&";  
            index++;
    }
            if (index == sizeOfParams){
 //add the last parameter without the "&"
             mStrToBeAppended+=  keyParams +mStrToBeAppended+= "=""?" + mParams.get(keyParamsmParams.size();
                    break;
                }
                mStrToBeAppended+=  keyParams-1).getName() + "=" + mParams.get(keyParamsmParams.size()+ "&";
-1).getValue();
            }
       
      //add the last parameter without the "&"}
            //mStrToBeAppended+= "?" + key + "=" + mParams.get(key);
        } //GET ENDS
        if(mTypeOfRequest.equalsIgnoreCase("POST")){
            Object key = null;
            isPostDataInJSONFormat = false;
            Iterator<Object>Iterator<String> it = mData.keySet().iterator();
                    while(it.hasNext()){
                key = it.next();
      String key = it.next();
       mParams.put(key, mData.get(key));
                //mPostDataListmParams.add(new BasicNameValuePair(String(key),new String(mData.get(key)));
                    }
            }
        } 
        }
        if ((mData == null) && (JSONStringDatajsonObj != null) && (mTypeOfRequest.equalsIgnoreCase("POST") == true)){
            isPostDataInJSONFormat = true;
        }
        
    }
    
    
    @Override 
    protected String doInBackground(String... baseUrls) {
    //android.os.Debug.waitForDebugger();    
        publishProgress(null);
        if(mTypeOfRequest.equalsIgnoreCase("GET")){
            String finalURL = baseUrls[0]+ mStrToBeAppended;
             return HttpUtility.GET(finalURL); 
        } 
        
        if (mTypeOfRequest.equalsIgnoreCase("POST") ){
            if(isPostDataInJSONFormat == false ){
 
                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPOSTMETHOd","Non-JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0],mParams );
            }
 
            if(isPostDataInJSONFormat ==else true){
                Log.i("JSONDATAPOSTMETHOd","JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0], JSONStringData);
            }
        }

        if (mTypeOfRequest.equalsIgnoreCase("PUT") ){
            if(isPostDataInJSONFormat == false ){

                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPUTMETHOd","Non-JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0],mParams mJSONPostData);
            }
 
            if(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPUTMETHOd","JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0], JSONStringData);
            }
        }
        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(); 
    }
}
import android.util.Base64;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;

public class HttpUtility { 

   
    private final static HttpClient mHhttpclient = new DefaultHttpClient();

    public static String GET(String url){
        Log.i("URL", url);
       InputStream inputStream = null;
       String result = "";
       try {

           HttpGet httpGet = new HttpGet(url);
           // make GET request to the given URL
           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               httpGet.addHeader("Authorization", "Basic " + auth);
           }
           HttpResponse httpResponse = mHhttpclient.execute(httpGet);

           // 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 POST(String url, LinkedHashMap<Object, Object> mParams){
    InputStream inputStream = null;
    String result = "";
    try{
        HttpPost post = new HttpPost(url);
        if(url.contains("@")){
            String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
            post.addHeader("Authorization", "Basic " + auth);
        }
        if(mParams != null){
            post.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>) mParams, "UTF-8"));
        }

        HttpResponse httpResponse = mHhttpclient.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, String jsonString){

       InputStream inputStream = null;
       String result = "";
        Log.i("JSONSTRINPUTDATA", jsonString );
       try{
           HttpPost post = new HttpPost(url);

           post.setHeader("Content-type", "application/json");

           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               post.addHeader("Authorization", "Basic " + auth);
           }

           //StringEntity se = new StringEntity(obj.toString());
           StringEntity se = new StringEntity(jsonString);
           //se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
           post.setEntity(se);

           HttpResponse httpResponse = mHhttpclient.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());
       }
       Log.i("JSONPOSTEND", "End of JSON data post methos...");
       Log.i("JSONPOSTDATARESULT", result);
       
       return result;
   }
    public static String PUTGET(String url, String jsonString){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpPut put = new HttpPut(url);
            put.setHeader("Content-type", "application/json");
            if(url.contains("@")){
                String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
                put.addHeader("Authorization", "Basic " + auth);
          // create }
HttpClient
            StringEntityHttpClient sehttpclient = new StringEntityDefaultHttpClient(jsonString);
   
          se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
     / make GET request to the given put.setEntity(se);
URL
            HttpResponse httpResponse = mHhttpclienthttpclient.execute(putnew 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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos...");

        return result;
    }
    
    public static String PUTPOST(String url, LinkedHashMap<Object, Object>List<NameValuePair> mParams){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpPutHttpClient puthttpclient = new HttpPutDefaultHttpClient(url);
            ifHttpPost post = new HttpPost(url);
            post.containssetEntity("@"new UrlEncodedFormEntity(mParams, "UTF-8")){;
            HttpResponse httpResponse = httpclient.execute(post);
             
    String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId +// ":"receive +response SignupOrLogIn.strPwd)as inputStream
            inputStream = httpResponse.getBytesgetEntity(),Base64.URL_SAFE|Base64.NO_WRAP)getContent();
 
            // convert inputstream to string
    put.addHeader        if("Authorization",inputStream "Basic!= "null){
 + auth              result = convertInputStreamToString(inputStream);
                //inputStream.close();
            }
                
            HttpResponseelse
 httpResponse               result = mHhttpclient"Did not work!";
 
        } catch (Exception e) {
            Log.executed(put"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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos...");

        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;
 
    }
}
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    private CallBack mCb; 
    LinkedHashMap<Object, Object> mData = null;
    //List mParams= new ArrayList(); 
    LinkedHashMap<Object, Object> mParams = new LinkedHashMap<>();
    List<NameValuePair> mPostDataList = new ArrayList<>();
    String mTypeOfRequest; 
    String mStrToBeAppended = "?";
    boolean isPostDataInJSONFormat = false;
    boolean JSonAndData = false;
    //JSONObject mJSONPostData = null;
    String JSONStringData = null;
    Context mContext = null;
    
    public HTTPAsyncTask(Context context, CallBack c, HashMap<Object, Object> data, String jsonString, String request) {
        mContext = context;
        mCb = c;
        mTypeOfRequest = request;
        JSONStringData = jsonString;
        //Log.i("JSONDATA", mJSONPostData.toString());
        if((data != null) && (jsonString == null)){
        mData = (LinkedHashMap)data;
        if(mTypeOfRequest.equalsIgnoreCase("GET")){
            Object key = null;
            Iterator<Object> it = mData.keySet().iterator();
            while(it.hasNext()){ 
                key = it.next(); 
                mParams.put(key, mData.get(key));
                Log.d("Data", key.toString() + " " + mData.get(key).toString());
                }
            Iterator<Object>itParams = mParams.keySet().iterator();
            int sizeOfParams = mParams.size();
            int index = 0;
            while(itParams.hasNext()){
                Object keyParams = itParams.next();
                index++;
                if (index == sizeOfParams){
                    mStrToBeAppended+=  keyParams + "=" + mParams.get(keyParams);
                    break;
                }
                mStrToBeAppended+=  keyParams + "=" + mParams.get(keyParams)+ "&";

            }
            //add the last parameter without the "&"
            //mStrToBeAppended+= "?" + key + "=" + mParams.get(key);
        } //GET ENDS
        if(mTypeOfRequest.equalsIgnoreCase("POST")){
            Object key = null;
            isPostDataInJSONFormat = false;
            Iterator<Object> it = mData.keySet().iterator();
            while(it.hasNext()){
                key = it.next();
                mParams.put(key, mData.get(key));
                //mPostDataList.add(new BasicNameValuePair(String(key),new String(mData.get(key)));
                }
            }
        } 
        
        if ((mData == null) && (JSONStringData != null) && (mTypeOfRequest.equalsIgnoreCase("POST") == true)){
            isPostDataInJSONFormat = true;
        }
    } 
    
    @Override 
    protected String doInBackground(String... baseUrls) {
    //android.os.Debug.waitForDebugger();
        publishProgress(null);
        if(mTypeOfRequest.equalsIgnoreCase("GET")){
        String finalURL = baseUrls[0]+ mStrToBeAppended;
        return HttpUtility.GET(finalURL); 
        } 
        
        if (mTypeOfRequest.equalsIgnoreCase("POST") ){
            if(isPostDataInJSONFormat == false ){
 
                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPOSTMETHOd","Non-JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0],mParams );
            }
 
            if(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPOSTMETHOd","JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0], JSONStringData);
            }
        }

        if (mTypeOfRequest.equalsIgnoreCase("PUT") ){
            if(isPostDataInJSONFormat == false ){

                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPUTMETHOd","Non-JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0],mParams );
            }
 
            if(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPUTMETHOd","JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0], JSONStringData);
            }
        }
        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(); 
    }
}
import android.util.Base64;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;

public class HttpUtility { 

   
    private final static HttpClient mHhttpclient = new DefaultHttpClient();

    public static String GET(String url){
        Log.i("URL", url);
       InputStream inputStream = null;
       String result = "";
       try {

           HttpGet httpGet = new HttpGet(url);
           // make GET request to the given URL
           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               httpGet.addHeader("Authorization", "Basic " + auth);
           }
           HttpResponse httpResponse = mHhttpclient.execute(httpGet);

           // 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 POST(String url, LinkedHashMap<Object, Object> mParams){
    InputStream inputStream = null;
    String result = "";
    try{
        HttpPost post = new HttpPost(url);
        if(url.contains("@")){
            String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
            post.addHeader("Authorization", "Basic " + auth);
        }
        if(mParams != null){
            post.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>) mParams, "UTF-8"));
        }

        HttpResponse httpResponse = mHhttpclient.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, String jsonString){

       InputStream inputStream = null;
       String result = "";
        Log.i("JSONSTRINPUTDATA", jsonString );
       try{
           HttpPost post = new HttpPost(url);

           post.setHeader("Content-type", "application/json");

           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               post.addHeader("Authorization", "Basic " + auth);
           }

           //StringEntity se = new StringEntity(obj.toString());
           StringEntity se = new StringEntity(jsonString);
           //se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
           post.setEntity(se);

           HttpResponse httpResponse = mHhttpclient.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());
       }
       Log.i("JSONPOSTEND", "End of JSON data post methos...");
       Log.i("JSONPOSTDATARESULT", result);
       
       return result;
   }
    public static String PUT(String url, String jsonString){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpPut put = new HttpPut(url);
            put.setHeader("Content-type", "application/json");
            if(url.contains("@")){
                String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
                put.addHeader("Authorization", "Basic " + auth);
            }

            StringEntity se = new StringEntity(jsonString);
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            put.setEntity(se);

            HttpResponse httpResponse = mHhttpclient.execute(put);

            // 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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos...");

        return result;
}

    public static String PUT(String url, LinkedHashMap<Object, Object> mParams){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpPut put = new HttpPut(url);
            if(url.contains("@")){
                String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
                put.addHeader("Authorization", "Basic " + auth);
            }

            HttpResponse httpResponse = mHhttpclient.execute(put);

            // 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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos...");

        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;

   }
}
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();
   }
}
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;
 
    }
}
added 6235 characters in body
Source Link
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    
    private CallBack mCb; 
    HashMap<StringLinkedHashMap<Object, String>Object> mData = null;
    List<NameValuePair>//List mParams= new ArrayList<NameValuePair>ArrayList(); 
    LinkedHashMap<Object, Object> mParams = new LinkedHashMap<>();
    List<NameValuePair> mPostDataList = new ArrayList<>();
    String mTypeOfRequest; 
    String mStrToBeAppended = "";"?";
    boolean isPostDataInJSONFormat = false;
    boolean JSonAndData = false;
    //JSONObject mJSONPostData = null;
    String JSONStringData = null;
    Context mContext = null;
    
    public HTTPAsyncTask(Context context, CallBack c, HashMap<StringHashMap<Object, String>Object> data, JSONObjectString jsonObjjsonString, String request) {
        mContext = context;
        mCb = c;
        mTypeOfRequest = request;
        mJSONPostDataJSONStringData = jsonObj;jsonString;
        //Log.i("JSONDATA", mJSONPostData.toString());
        if((data != null) && (jsonObjjsonString == null)){
            mData = (LinkedHashMap)data;
            if(mTypeOfRequest.equalsIgnoreCase("GET")){
            Object key = null;
    Iterator<String>        Iterator<Object> it = mData.keySet().iterator();
                while(it.hasNext()){
      
               String key = it.next(); 
                mParams.put(key, mData.get(key));
   mParams             Log.addd(new"Data", BasicNameValuePair(key,.toString() + " " + mData.get(key).toString());
                }
            Iterator<Object>itParams = mParams.keySet().iterator();
  for (         int isizeOfParams = 0; i<mParamsmParams.size()-1; i++){;
            int index = 0;
     mStrToBeAppended+= "?" + mParams.get(i).getName() + "=" + mParams.getwhile(i)itParams.getValuehasNext()){
 + "&"; 
              Object keyParams = }itParams.next();
                //addindex++;
 the last parameter without the "&"          if (index == sizeOfParams){
                    mStrToBeAppended+= "?" keyParams + "=" + mParams.get(mParams.size()-1).getName(keyParams);
                    break;
                }
                mStrToBeAppended+=  keyParams + "=" + mParams.get(mParams.size()-1).getValue(keyParams);+ "&";

            }
    
         //add the last parameter without the }"&"
            //mStrToBeAppended+= "?" + key + "=" + mParams.get(key);
        } //GET ENDS
        if(mTypeOfRequest.equalsIgnoreCase("POST")){
            Object key = null;
            Iterator<String>isPostDataInJSONFormat = false;
            Iterator<Object> it = mData.keySet().iterator();
                    while(it.hasNext()){
                        String key = it.next();
                mParams.put(key, mData.get(key));
                mParams//mPostDataList.add(new BasicNameValuePair(String(key),new String(mData.get(key)));
                    }
            }
        } 
        }
        if ((mData == null) && (jsonObjJSONStringData != null) && (mTypeOfRequest.equalsIgnoreCase("POST") == true)){
            isPostDataInJSONFormat = true;
        }
        
    }
    
    
    @Override 
    protected String doInBackground(String... baseUrls) {
        //android.os.Debug.waitForDebugger();
        publishProgress(null);
        if(mTypeOfRequest.equalsIgnoreCase("GET")){
            String finalURL = baseUrls[0]+ mStrToBeAppended;
             return HttpUtility.GET(finalURL); 
        } 
        
        if (mTypeOfRequest.equalsIgnoreCase("POST") ){
            if(isPostDataInJSONFormat == false ){ 

                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPOSTMETHOd","Non-JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0],mParams );
            } 

            elseif(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPOSTMETHOd","JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0], mJSONPostDataJSONStringData);
            }
        }

        if (mTypeOfRequest.equalsIgnoreCase("PUT") ){
            if(isPostDataInJSONFormat == false ){

                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPUTMETHOd","Non-JSON PUT method to be called...");
                return null;HttpUtility.PUT(baseUrls[0],mParams );
            }

            if(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPUTMETHOd","JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0], JSONStringData);
            }
        }
        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(); 
    }
}
import android.util.Base64;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;

public class HttpUtility { 

   
    private final static HttpClient mHhttpclient = new DefaultHttpClient();

    public static String GET(String url){
        Log.i("URL", url);
       InputStream inputStream = null;
        String result = "";
        try {
 
           HttpGet httpGet = new HttpGet(url);
           // createmake HttpClient
GET request to the given URL
       HttpClient httpclient = new DefaultHttpClientif(url.contains("@");){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
            // make GET requesthttpGet.addHeader("Authorization", to"Basic the" given+ URLauth);
           }
           HttpResponse httpResponse = httpclientmHhttpclient.execute(new HttpGet(url)httpGet);
 
            // 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());
       }

      else return result;
   }



public static String POST(String url, LinkedHashMap<Object, Object> mParams){
    InputStream inputStream = null;
    String result = "Did"";
 not work!";
  try{
        }HttpPost catchpost (Exception= enew HttpPost(url);
        if(url.contains("@")){
            LogString auth =new String(Base64.dencode("InputStream",( eSignupOrLogIn.getLocalizedMessagestrLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
            post.addHeader("Authorization", "Basic " + auth);
        }
        if(mParams != null){
        return result;   post.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>) mParams, "UTF-8"));
        }

        HttpResponse httpResponse = mHhttpclient.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, List<NameValuePair>String mParamsjsonString){

       InputStream inputStream = null;
       String result = "";
        Log.i("JSONSTRINPUTDATA", jsonString );
       try{
           HttpPost post = new HttpPost(url);

           post.setHeader("Content-type", "application/json");

           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               post.addHeader("Authorization", "Basic " + auth);
           }

           //StringEntity se = new StringEntity(obj.toString());
           StringEntity se = new StringEntity(jsonString);
           //se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
           post.setEntity(se);

           HttpResponse httpResponse = mHhttpclient.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());
       }
       Log.i("JSONPOSTEND", "End of JSON data post methos...");
       Log.i("JSONPOSTDATARESULT", result);
       
       return result;
   }
    public static String PUT(String url, String jsonString){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpClientHttpPut httpclientput = new DefaultHttpClientHttpPut(url);
            HttpPostput.setHeader("Content-type", post"application/json");
 = new HttpPost         if(url.contains("@");){
            post    String auth =new String(Base64.setEntityencode(new( UrlEncodedFormEntitySignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(mParams), "UTF-8"Base64.URL_SAFE|Base64.NO_WRAP));
            HttpResponse httpResponse   put.addHeader("Authorization", "Basic " + auth);
            }

            StringEntity se = httpclientnew StringEntity(jsonString);
            se.executesetContentEncoding(postnew BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            put.setEntity(se); 

            HttpResponse httpResponse = mHhttpclient.execute(put);

            // 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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos...");

        return result;
        
        
    } 

    public static String POSTPUT(String url, JSONObjectLinkedHashMap<Object, objObject> mParams){
        
        InputStream inputStream = null;
        String result = "";
        
        HttpClient httpclient = new DefaultHttpClient();

        try{
            HttpPostHttpPut postput = new HttpPostHttpPut(url);
            postif(url.setHeadercontains("Content-type", "application/json""@");){
            
        String auth =new String(Base64.encode(( StringEntitySignupOrLogIn.strLogInId se+ =":" new+ StringEntity(objSignupOrLogIn.toStringstrPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP)); 
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        put.addHeader("Authorization", "Basic " + post.setEntity(seauth);
            }

            HttpResponse httpResponse = httpclientmHhttpclient.execute(postput);
            
            // 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 = bufferedReaderLog.readLinei()) != null)
            result += line;
 
  "JSONPUTEND", "End of JSON data put inputStreammethos.close(.."); 

        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;

   }
}
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();
   }
}
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;
 
    }
}
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    private CallBack mCb; 
    LinkedHashMap<Object, Object> mData = null;
    //List mParams= new ArrayList(); 
    LinkedHashMap<Object, Object> mParams = new LinkedHashMap<>();
    List<NameValuePair> mPostDataList = new ArrayList<>();
    String mTypeOfRequest; 
    String mStrToBeAppended = "?";
    boolean isPostDataInJSONFormat = false;
    boolean JSonAndData = false;
    //JSONObject mJSONPostData = null;
    String JSONStringData = null;
    Context mContext = null;
    
    public HTTPAsyncTask(Context context, CallBack c, HashMap<Object, Object> data, String jsonString, String request) {
        mContext = context;
        mCb = c;
        mTypeOfRequest = request;
        JSONStringData = jsonString;
        //Log.i("JSONDATA", mJSONPostData.toString());
        if((data != null) && (jsonString == null)){
        mData = (LinkedHashMap)data;
        if(mTypeOfRequest.equalsIgnoreCase("GET")){
            Object key = null;
            Iterator<Object> it = mData.keySet().iterator();
            while(it.hasNext()){  
                key = it.next(); 
                mParams.put(key, mData.get(key));
                Log.d("Data", key.toString() + " " + mData.get(key).toString());
                }
            Iterator<Object>itParams = mParams.keySet().iterator();
            int sizeOfParams = mParams.size();
            int index = 0;
            while(itParams.hasNext()){
                Object keyParams = itParams.next();
                index++;
                if (index == sizeOfParams){
                    mStrToBeAppended+=  keyParams + "=" + mParams.get(keyParams);
                    break;
                }
                mStrToBeAppended+=  keyParams + "=" + mParams.get(keyParams)+ "&";

            }
            //add the last parameter without the "&"
            //mStrToBeAppended+= "?" + key + "=" + mParams.get(key);
        } //GET ENDS
        if(mTypeOfRequest.equalsIgnoreCase("POST")){
            Object key = null;
            isPostDataInJSONFormat = false;
            Iterator<Object> it = mData.keySet().iterator();
            while(it.hasNext()){
                key = it.next();
                mParams.put(key, mData.get(key));
                //mPostDataList.add(new BasicNameValuePair(String(key),new String(mData.get(key)));
                }
            }
        } 
        
        if ((mData == null) && (JSONStringData != null) && (mTypeOfRequest.equalsIgnoreCase("POST") == true)){
            isPostDataInJSONFormat = true;
        }
    } 
    
    @Override 
    protected String doInBackground(String... baseUrls) {
    //android.os.Debug.waitForDebugger();
        publishProgress(null);
        if(mTypeOfRequest.equalsIgnoreCase("GET")){
        String finalURL = baseUrls[0]+ mStrToBeAppended;
        return HttpUtility.GET(finalURL); 
        } 
        
        if (mTypeOfRequest.equalsIgnoreCase("POST") ){
            if(isPostDataInJSONFormat == false ){ 

                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPOSTMETHOd","Non-JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0],mParams );
            } 

            if(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPOSTMETHOd","JSON POST method to be called...");
                return HttpUtility.POST(baseUrls[0], JSONStringData);
            }
        }

        if (mTypeOfRequest.equalsIgnoreCase("PUT") ){
            if(isPostDataInJSONFormat == false ){

                if( JSonAndData == false){
                    mParams = null;
                }
                Log.i("NONJSONDATAPUTMETHOd","Non-JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0],mParams );
            }

            if(isPostDataInJSONFormat == true){
                Log.i("JSONDATAPUTMETHOd","JSON PUT method to be called...");
                return HttpUtility.PUT(baseUrls[0], JSONStringData);
            }
        }
        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(); 
    }
}
import android.util.Base64;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;

public class HttpUtility { 

   
    private final static HttpClient mHhttpclient = new DefaultHttpClient();

    public static String GET(String url){
        Log.i("URL", url);
       InputStream inputStream = null;
       String result = "";
       try {

           HttpGet httpGet = new HttpGet(url);
           // make GET request to the given URL
           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               httpGet.addHeader("Authorization", "Basic " + auth);
           }
           HttpResponse httpResponse = mHhttpclient.execute(httpGet);

           // 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 POST(String url, LinkedHashMap<Object, Object> mParams){
    InputStream inputStream = null;
    String result = "";
    try{
        HttpPost post = new HttpPost(url);
        if(url.contains("@")){
            String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
            post.addHeader("Authorization", "Basic " + auth);
        }
        if(mParams != null){
            post.setEntity(new UrlEncodedFormEntity((List<? extends NameValuePair>) mParams, "UTF-8"));
        }

        HttpResponse httpResponse = mHhttpclient.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, String jsonString){

       InputStream inputStream = null;
       String result = "";
        Log.i("JSONSTRINPUTDATA", jsonString );
       try{
           HttpPost post = new HttpPost(url);

           post.setHeader("Content-type", "application/json");

           if(url.contains("@")){
               String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
               post.addHeader("Authorization", "Basic " + auth);
           }

           //StringEntity se = new StringEntity(obj.toString());
           StringEntity se = new StringEntity(jsonString);
           //se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
           post.setEntity(se);

           HttpResponse httpResponse = mHhttpclient.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());
       }
       Log.i("JSONPOSTEND", "End of JSON data post methos...");
       Log.i("JSONPOSTDATARESULT", result);
       
       return result;
   }
    public static String PUT(String url, String jsonString){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpPut put = new HttpPut(url);
            put.setHeader("Content-type", "application/json");
            if(url.contains("@")){
                String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
                put.addHeader("Authorization", "Basic " + auth);
            }

            StringEntity se = new StringEntity(jsonString);
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            put.setEntity(se); 

            HttpResponse httpResponse = mHhttpclient.execute(put);

            // 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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos...");

        return result;
} 

    public static String PUT(String url, LinkedHashMap<Object, Object> mParams){
        InputStream inputStream = null;
        String result = "";
        try{
            HttpPut put = new HttpPut(url);
            if(url.contains("@")){
                String auth =new String(Base64.encode(( SignupOrLogIn.strLogInId + ":" + SignupOrLogIn.strPwd).getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
                put.addHeader("Authorization", "Basic " + auth);
            }

            HttpResponse httpResponse = mHhttpclient.execute(put);

            // 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());
        }
        Log.i("JSONPUTEND", "End of JSON data put methos..."); 

        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;

   }
}
formatting
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

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);

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 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;
     
        }
    }

**`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 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:**
//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);

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 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;
 
    }
}

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 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:

//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);
deleted 216 characters in body
Source Link
Loading
deleted 322 characters in body
Source Link
Loading
deleted 46 characters in body
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237
Loading
Rollback to Revision 6
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237
Loading
added 114 characters in body
Source Link
Loading
edited tags
Link
Malachi
  • 28.7k
  • 11
  • 86
  • 188
Loading
added 14 characters in body
Source Link
Loading
added 1631 characters in body
Source Link
Loading
edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Loading
edited tags
Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237
Loading
Source Link
Loading