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

Android 的 HTTP 兩種請求模式:GET 與 POST

編輯:Android 開發教學

Android 的 SDK 內含 org.apache.http 套件,因此可直接使用 HTTP 請求相關類別,無需額外導入 JAR。

GET 請求

GET 通常用於向伺服器索取資料,參數會附加在網址後方。

String serverURL = "https://example.com/api?username=abc";
HttpGet httpRequest = new HttpGet(serverURL);
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
    String result = EntityUtils.toString(httpResponse.getEntity());
}

POST 請求

POST 通常用於向伺服器傳送資料,參數會放在請求主體中,適合傳輸較多或較敏感的內容。

String uriAPI = "https://example.com/api";
HttpPost httpRequest = new HttpPost(uriAPI);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("str", "I am Post String"));
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
    String strResult = EntityUtils.toString(httpResponse.getEntity());
}

GET 與 POST 的差異主要在資料傳遞方式與使用情境。GET 適合查詢,POST 適合提交。

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