在HttpAsyncTask()传递参数。执行() [英] Passing parameters in HttpAsyncTask().execute()

查看:664
本文介绍了在HttpAsyncTask()传递参数。执行()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JSON和HTTP POST及以下code结构,我的Andr​​oid应用程序的帖子串到Web服务器使用,但我想一些参数传递给AsyncTask的<通>类HttpAsyncTask()执行(从这里开始。 )。任何一个可以帮助我该怎么办呢..你的帮助会感激我在此先感谢

  btn_send.setOnClickListener(新OnClickListener(){
 @覆盖
        公共无效的onClick(视图v){
            // TODO自动生成方法存根
            字符串strData是=一些字符串张贴
            字符串strURL =HTTP://我-URL /;
            字符串reqTimeOut =30000;
            字符串code =9990001;
            字符串的WebRequest = SendWebRequest(strURL,strData是,reqTimeOut,code); //方法来发送HTTpPost要求        将writeToFile(WebRequest的); //写入响应于文件私人字符串SendWebRequest(字符串urlStr,字符串数据,字符串reqTimeOut,字符串code)       {
            // TODO自动生成方法存根            字符串结果=;
            尝试
            {
                / *                           对数据的一些强制性操作
                 * /
                   //这里我想通过参数:url,reqTimeout,数据,文本和值(设置头),以POST方法。
                   新HttpAsyncTask()执行(urlStr);            }赶上(例外五){}            返回结果;
      }
公共类HttpAsyncTask扩展的AsyncTask<弦乐,太虚,字符串> {    @覆盖
    保护字符串doInBackground(字符串... PARAMS){
        // TODO自动生成方法存根
         返回POST(PARAMS [0]);
    }    // onPostExecute显示的AsyncTask的结果。
    @覆盖
    保护无效onPostExecute(字符串结果){
        Toast.makeText(getBaseContext(),发送的数据!,Toast.LENGTH_LONG).show();
   }    私人字符串POST(最终字符串URL,最后弦乐POSTDATA,文本字符串,字符串值){
        // TODO自动生成方法存根        InputStream的InputStream的;
        字符串结果=;
        尝试{            // 1.创建HttpClient的
            HttpClient的HttpClient的=新DefaultHttpClient();            // 2.化妆POST请求到指定的URL
            HttpPost httpPost =新HttpPost(URL);
            MainActivity.this.runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      Toast.makeText(getApplicationContext()2.网址为+网址,
                           Toast.LENGTH_LONG).show();
                  }
                });            JSON字符串= POSTDATA;         // 5.设置JSON来StringEntity
            StringEntity SE =新StringEntity(JSON);            // 6集httpPost实体
            httpPost.setEntity(SE);
          // HttpConnectionParams.setConnectionTimeout(空300000);            // 7.设置一些头通知服务器有关内容的类型
           // httpPost.setHeader(接受,应用/ JSON);
            httpPost.setHeader(文字,值);            // 8.执行POST请求到指定的URL
            HTT presponse HTT presponse = httpclient.execute(httpPost);            // 9.收到响应为InputStream的
            的InputStream = HTT presponse.getEntity()的getContent()。            // 10.转换的InputStream串
            如果(的InputStream!= NULL){
                结果= convertInputStreamToString(InputStream的);            }
            其他
                结果=没有工作!        }赶上(例外五){
            Log.d(InputStream的,e.getLocalizedMessage());
        }
     // 11返回结果
        返回结果;
    }


解决方案

编写您HttpAsyncTask类参数化的构造函数。添加你想在你的HttpAsyncTask类中使用私有字段。然后,只需实例化HttpAsyncTask类对象与所需的参数。

您的阶级结构想:

 公共类HttpAsyncTask扩展的AsyncTask<弦乐,太虚,字符串> {    私人字符串URL,reqTimeout,数据,文字,价值;
        公共HttpAsyncTask(URL字符串,字符串reqTimeout,字符串数据,文本字符串,字符串值){
    this.url =网址;
    this.reqTimeout = reqTimeout;
    this.data =数据;
    this.text =文本;
    THIS.VALUE =价值;
    }
        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            // TODO自动生成方法存根
             返回POST(PARAMS [0]);
        }        // onPostExecute显示的AsyncTask的结果。
        @覆盖
        保护无效onPostExecute(字符串结果){
            Toast.makeText(getBaseContext(),发送的数据!,Toast.LENGTH_LONG).show();
       }        私人字符串POST(最终字符串URL,最后弦乐POSTDATA,文本字符串,字符串值){
            // TODO自动生成方法存根            InputStream的InputStream的;
            字符串结果=;
            尝试{                // 1.创建HttpClient的
                HttpClient的HttpClient的=新DefaultHttpClient();                // 2.化妆POST请求到指定的URL
                HttpPost httpPost =新HttpPost(URL);
                MainActivity.this.runOnUiThread(新的Runnable(){
                      公共无效的run(){
                          Toast.makeText(getApplicationContext()2.网址为+网址,
                               Toast.LENGTH_LONG).show();
                      }
                    });                JSON字符串= POSTDATA;             // 5.设置JSON来StringEntity
                StringEntity SE =新StringEntity(JSON);                // 6集httpPost实体
                httpPost.setEntity(SE);
              // HttpConnectionParams.setConnectionTimeout(空300000);                // 7.设置一些头通知服务器有关内容的类型
               // httpPost.setHeader(接受,应用/ JSON);
                httpPost.setHeader(文字,值);                // 8.执行POST请求到指定的URL
                HTT presponse HTT presponse = httpclient.execute(httpPost);                // 9.收到响应为InputStream的
                的InputStream = HTT presponse.getEntity()的getContent()。                // 10.转换的InputStream串
                如果(的InputStream!= NULL){
                    结果= convertInputStreamToString(InputStream的);                }
                其他
                    结果=没有工作!            }赶上(例外五){
                Log.d(InputStream的,e.getLocalizedMessage());
            }
         // 11返回结果
            返回结果;
        }

然后当你调用HttpAsyncTask类的execute方法,你应该把它在下列方式:

HttpAsyncTask httpAsyncTask =新HttpAsyncTask(URL,reqTimeout,数据,文字,价值);
  httpAsyncTask()执行(urlStr);

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

解决方案

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

这篇关于在HttpAsyncTask()传递参数。执行()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆