android http post asynctask

前端 未结 2 2055
萌比男神i
萌比男神i 2020-12-04 23:19

Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found we

相关标签:
2条回答
  • 2020-12-04 23:47

    At first, You put a class like following:

    public class AsyncHttpPost extends AsyncTask<String, String, String> {
        interface Listener {
            void onResult(String result);
        }
        private Listener mListener;
        private HashMap<String, String> mData = null;// post data
    
        /**
         * constructor
         */
        public AsyncHttpPost(HashMap<String, String> data) {
            mData = data;
        }
        public void setListener(Listener listener) {
            mListener = listener;
        }
    
        /**
         * background
         */
        @Override
        protected String doInBackground(String... params) {
            byte[] result = null;
            String str = "";
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
            try {
                // set up post data
                ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                Iterator<String> it = mData.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
                }
    
                post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
                HttpResponse response = client.execute(post);
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                    result = EntityUtils.toByteArray(response.getEntity());
                    str = new String(result, "UTF-8");
                }
            }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            catch (Exception e) {
            }
            return str;
        }
    
        /**
         * on getting result
         */
        @Override
        protected void onPostExecute(String result) {
            // something...
            if (mListener != null) {
                mListener.onResult(result)
            }
        }
    }
    

    Now. You just write some lines like following:

    HashMap<String, String> data = new HashMap<String, String>();
    data.put("key1", "value1");
    data.put("key2", "value2");
    AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
    asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
        @Override
        public void onResult(String result) {
            // do something, using return value from network
        }
    });
    asyncHttpPost.execute("http://example.com");
    
    0 讨论(0)
  • 2020-12-04 23:56

    First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.

    public AsyncTask <Params,Progress,Result> {
    
    }
    

    so in your task you should go like this

    public MyTask extends<String,Void,Void>{
    
    public Void doInBackground(String... params){//those Params are String because it's declared like that
    
    }
    
    }
    

    To use it, it's quite simple

    new MyTask().execute("param1","param2","param3")
    
    0 讨论(0)
提交回复
热议问题