How to send data to a website using httpPost, app crashes [duplicate]

主宰稳场 提交于 2019-12-02 02:58:55

Networking operation on UI Main thread are not allowed.

Try following code.

public class NetRequestAsync extends AsyncTask<Void, Void, Boolean> {

    String id, msg;

    public NetRequestAsync(String id, String message) {
        this.id = id;
        this.msg = message;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.eeecoderpages.orgfree.com/post.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs.add(new BasicNameValuePair("id", id));
            nameValuePairs.add(new BasicNameValuePair("message", msg));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);
            return true;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if(result){
            //successful request
        }else{
            //error in request response
        }
        msgTextField.setText(""); // clear text box
    }

}

To use this code,

NetRequestAsync request = new NetRequestAsync("12345","Hi");
request.execute();

Note

UI operation like updating TextView, EditText or setting image to ImageView are not allowed in doInBackground() method. You can do that in onPostExecute() or onPreExecute().

You are doing a network related operation on the main ui thread. Use a thread or asynctask.

You will get NetworkOnMainThreadexception post honeycomb.

      new PostTask().execute();

AsyncTask

 class PostTask extends AsyncTask<Void,Void,Void>
 {
      @Override
      protected void doInbackground(Void... params)
      {
             // network related operation
             // do not update ui here
             // your http post here
      }
 } 

Also if you use threads or asynctask remember not to update ui in doInbackgroud.

You have this

      String msg = msgTextField.getText().toString();  
      // you can pass msg to asynctask doInbackground or to the asynctask contructor
      msgTextField.setText(""); 

Use onPreExecute and onPostExecute for ui updation.

It sound like you are getting NetworkOnMainThread Exception

Reason: you are performing Network Operation on Main UI Thread

Solution: use AsyncTask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!