jaimin
jaimin

Reputation: 563

Passing parameters in HttpAsyncTask().execute()

My android app posts a string to web server using json and Http post and following code structure is used, but i want to pass few parameters to AsyncTask<> class through HttpAsyncTask().execute("from here"). can any one help me how to do it.. your help will be greatful for me thanks in advance

btn_send.setOnClickListener(new OnClickListener(){
 @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String strData = "Some String to post";
            String strURL = "http://My-Url/";   
            String reqTimeOut = "30000";  
            String Code = "9990001" ;
            String webRequest = SendWebRequest(strURL,strData, reqTimeOut, Code);// method to send HTTpPost request

        WriteToFile(webRequest);//writing response to file



private String SendWebRequest(String urlStr, String Data,String reqTimeOut, String Code)          

       {
            // TODO Auto-generated method stub

            String result="";
            try
            {
                /*

                           Some mandatory operations on Data
                 */


                   // Here i want to pass parameters: url, reqTimeout, Data, text and value(for setting header)  to POST method. 
                   new HttpAsyncTask().execute(urlStr);

            }catch(Exception e){}

            return result;
      }
public class HttpAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
         return POST(params[0]);
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
   }

    private String POST(final String url, final String postData,String text, String value) {
        // TODO Auto-generated method stub

        InputStream inputStream ;
        String result = "";


        try {



            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            MainActivity.this.runOnUiThread(new Runnable() {
                  public void run() {
                      Toast.makeText(getApplicationContext(), "2. url is "+url,
                           Toast.LENGTH_LONG).show();
                  }
                });

            String json=postData ;         

         // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);
          //  HttpConnectionParams.setConnectionTimeout(null, 300000);

            // 7. Set some headers to inform server about the type of the content   
           // httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader(text, value);

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(inputStream != null){
                result = convertInputStreamToString(inputStream);

            }
            else
                result = "Did not work!";

        } catch (Exception e) {


            Log.d("InputStream", e.getLocalizedMessage());
        }
     // 11. return result
        return result;
    }

Upvotes: 1

Views: 2702

Answers (1)

Pankaj Deshpande
Pankaj Deshpande

Reputation: 502

Write parameterised constructor for your HttpAsyncTask class. Add private field which you want to use in your HttpAsyncTask class. Then just instantiate the HttpAsyncTask class object with required parameters.

Your class structure would like:

public class HttpAsyncTask extends AsyncTask<String, Void, String> {

    private String url,reqTimeout,data,text,value;
        public  HttpAsyncTask(String url,String reqTimeout,String data, String text, String value){
    this.url = url;
    this.reqTimeout = reqTimeout;
    this.data = data;
    this.text = text;
    this.value = value;
    }
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
             return POST(params[0]);
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }

        private String POST(final String url, final String postData,String text, String value) {
            // TODO Auto-generated method stub

            InputStream inputStream ;
            String result = "";


            try {



                // 1. create HttpClient
                HttpClient httpclient = new DefaultHttpClient();

                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost(url);
                MainActivity.this.runOnUiThread(new Runnable() {
                      public void run() {
                          Toast.makeText(getApplicationContext(), "2. url is "+url,
                               Toast.LENGTH_LONG).show();
                      }
                    });

                String json=postData ;         

             // 5. set json to StringEntity
                StringEntity se = new StringEntity(json);

                // 6. set httpPost Entity
                httpPost.setEntity(se);
              //  HttpConnectionParams.setConnectionTimeout(null, 300000);

                // 7. Set some headers to inform server about the type of the content   
               // httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader(text, value);

                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPost);

                // 9. receive response as inputStream
                inputStream = httpResponse.getEntity().getContent();

                // 10. convert inputstream to string
                if(inputStream != null){
                    result = convertInputStreamToString(inputStream);

                }
                else
                    result = "Did not work!";

            } catch (Exception e) {


                Log.d("InputStream", e.getLocalizedMessage());
            }
         // 11. return result
            return result;
        }

And then when you call the execute method of HttpAsyncTask class, you should call it in following way:

HttpAsyncTask httpAsyncTask = new HttpAsyncTask(url,reqTimeout,data, text,value); httpAsyncTask().execute(urlStr);

Upvotes: 1

Related Questions