gpt4 book ai didi

java - Android HTTP post 请求点击按钮

转载 作者:行者123 更新时间:2023-12-02 00:15:52 24 4
gpt4 key购买 nike

我想通过单击按钮向我的网站发送 HTTP POST 请求。我搜索allot只找到了这段代码

// 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
}
}

并在按钮上单击 Start AsyncTask onbuttonclickHttpPost 为:

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

}
});

关于java - Android HTTP post 请求点击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11899793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com