如何在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中文網其他相關文章!