我想通过点击按钮来我的网站发送一个HTTP POST请求。我搜索配发只发现了这片code
i want to send an HTTP post request by Clicking on Button to my website. i searched allot only found this piece of code
// 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
}
但我不知道它与按钮的点击是如何工作的。
But i don't know how it work with an clicking on button.
使用的AsyncTask 对按钮点击执行网络Opertion为:
use AsyncTask for Performing Network Opertion on Button Click as:
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
}
}
和按钮上单击开始AsyncTask的onbuttonclickHttpPost为:
and on Button Click Start AsyncTask onbuttonclickHttpPost as:
buttonclick.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
new onbuttonclickHttpPost.execute(null);
}
});