在 Android 中发送 POST 数据 [英] Sending POST data in Android
问题描述
我对 PHP、JavaScript 和许多其他脚本语言有经验,但对 Java 或 Android 没有太多经验.
I'm experienced with PHP, JavaScript and a lot of other scripting languages, but I don't have a lot of experience with Java or Android.
我正在寻找一种将 POST 数据发送到 PHP 脚本并显示结果的方法.
I'm looking for a way to send POST data to a PHP script and display the result.
推荐答案
注意(2020 年 10 月):Android API 级别 30 中已弃用以下答案中使用的 AsyncTask.请参阅 官方文档 或 这篇博文 一个更新的例子
Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example
更新(2017 年 6 月)适用于 Android 6.0+ 的答案.感谢 @Rohit Suthar,@Tamis Bolvari 和 @sudhiskr 的评论.
Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI(){
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
参考文献:
- https://developer.android.com/reference/java/net/HttpURLConnection.html
- 如何使用 NameValuePair 使用 POST 向 HttpURLConnection 添加参数
原始答案(2010 年 5 月)
注意:此解决方案已过时.它仅适用于 5.1 以下的 Android 设备.Android 6.0 及更高版本不包括此答案中使用的 Apache http 客户端.
来自 Apache Commons 的 Http 客户端是要走的路.它已经包含在android中.这是一个如何使用它进行 HTTP Post 的简单示例.
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// 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", "Hi"));
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
}
}
这篇关于在 Android 中发送 POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!