在Android 中發送POST 資料
POST 請求用於將資料發送到伺服器以建立或更新資源,通常在網頁表單的形式。在本例中,任務是將 POST 資料傳送到伺服器上的 PHP 腳本並顯示結果。
解決方案(針對 Android 6.0 更新):
建議的方法是使用 HttpURLConnection 類別。以下是示範如何傳送POST 資料的Java 程式碼片段:
public class CallAPI extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String urlString = params[0]; String data = params[1]; 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()); } return null; } }
原始解決方案(對於Android 6.0 已過時):
在Android 6.0 之前,Apache HttpClient 庫可用於HTTP Post要求:
public void postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 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中使用HttpURLConnection發送POST資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!