gpt4 book ai didi

java - 使用 Android 通过 HttpRequest 发送简单的 POST

转载 作者:行者123 更新时间:2023-11-29 21:44:23 26 4
gpt4 key购买 nike

我希望我的应用程序通过查询字符串将两个字符串发送到一个 php 文件,该文件将把它们作为 POST 变量处理。

到目前为止我有这段代码

public void postData() {    
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31");

try {

HttpResponse response = httpclient.execute(httppost);

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

我认为这是一个容易解决的问题,但这是我的第一个 Android 应用程序,我将不胜感激所有帮助。

最佳答案

使用 nameValuePairs 在 POST 请求中传递数据。

像这样尝试:

public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");

try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}

关于java - 使用 Android 通过 HttpRequest 发送简单的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256717/

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