我想通过单击按钮发送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 }
但是我不知道如何通过单击按钮来工作。
使用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); } });