Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中使用 POST 請求與伺服器通訊

編輯:關於 Android 程式設計

在網頁開發中,我們常用 jQuery 的 $.post() 輕鬆發起 POST 請求;同樣地,在 Android 應用中也常需要向伺服器提交資料並取得回應,這時就得使用 POST 請求。本文說明其思路與實作。

主要用到的類別

在 Android 中實作 POST 請求,主要會用到 HttpPost、HttpResponse 與 EntityUtils。

實作思路

  1. 建立 HttpPost 實例,設定要請求的伺服器 URL。
  2. 為 HttpPost 設定參數,使用鍵值對的 NameValuePair 類別。
  3. 發起 POST 請求,取得回傳的 HttpResponse。
  4. 以 EntityUtils 處理回傳的實體(可取得字串或 byte 陣列)。

使用 HttpPost 的範例

public class HttpURLActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = "https://192.168.2.112:8080/JustsyApp/Applet";

        // 第一步:建立 HttpPost 物件
        HttpPost httpPost = new HttpPost(url);

        // 以 NameValuePair 設定 POST 參數
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("action", "downloadAndroidApp"));
        params.add(new BasicNameValuePair("packageId", "89dcb664-50a7-4bf2-aeed-49c08af6a58a"));
        params.add(new BasicNameValuePair("uuid", "test_ok1"));

        HttpResponse httpResponse = null;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            httpResponse = new DefaultHttpClient().execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 第三步:以 getEntity 取得結果
                String result = EntityUtils.toString(httpResponse.getEntity());
                System.out.println("result:" + result);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        setContentView(R.layout.main);
    }
}

補充:使用 HttpURLConnection 進行 POST

除了 Apache HttpClient,也可使用 HttpURLConnection:

String path = "https://192.168.2.115:8080/android-web-server/httpConnectServlet.do?PackageID=89dcb664-50a7-4bf2-aeed-49c08af6a58a";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
System.out.println(conn.getResponseCode());

重要提醒

網路請求屬於耗時操作,切勿在主執行緒(UI Thread)中直接執行,否則在較新版 Android 上會出 NetworkOnMainThreadException。建議改用 AsyncTask、Thread 或 Kotlin 協程等方式放到背景執行緒。此外,別忘了在 Manifest 中加入 android.permission.INTERNET 權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved