小编典典

单击按钮的Android HTTP发布请求

java

我想通过单击按钮发送HTTP发布请求到我的网站。我搜索分配只发现了这段代码

// Create a new HttpClient and Post Header

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

但是我不知道如何通过单击按钮来工作。


阅读 221

收藏
2020-11-30

共1个答案

小编典典

使用AsyncTask在按钮单击时执行网络操作为:

public class onbuttonclickHttpPost extends AsyncTask<String, Void, Void> {
    @Override
    protected String doInBackground(String... params) {
        byte[] result = null;
        String str = "";
       // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

        try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("id", "12345"));
                nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                result = EntityUtils.toByteArray(response.getEntity());
                str = new String(result, "UTF-8");
            }
          } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }  
        return str;
    }

    /**
     * on getting result
     */
    @Override
    protected void onPostExecute(String result) {
        // something with data retrieved from server in doInBackground
    }
}

然后在Button上单击Start AsyncTask onbuttonclickHttpPost作为:

buttonclick.setOnClickListener(new View.OnClickListener()
        {
         public void onClick(View v) {
         new onbuttonclickHttpPost.execute(null);

     }
      });
2020-11-30