如何在 Android 中发送 POST 数据
对于精通 PHP、JavaScript 和其他脚本语言但不熟悉 Java 和 Android 的开发人员,本指南提供了将 POST 数据发送到 PHP 脚本并显示结果的解决方案。
已更新方法 (Android 6.0 )
此更新的解决方案利用 AsyncTask,推荐用于 Android 中的后台任务。
public class CallAPI extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String urlString = params[0]; // URL to call String data = params[1]; // Data to post try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); OutputStream 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()); } } }
原始方法(Android 5.1 及以下)
对于运行 Android 5.1 及以下版本的设备,Apache HttpClient 可以使用:
public void postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); try { HttpResponse response = httpclient.execute(httppost); } catch (Exception e) { // Handle exceptions } }
以上是如何从 Android 将 POST 数据发送到 PHP 脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!