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

Android 使用 HttpURLConnection 與 HttpClient 進行網路編程

編輯:關於 Android 程式設計

Android 使用 HttpURLConnection 與 HttpClient 進行網路編程

Android 中常見的 HTTP 網路請求方式,包括 HttpURLConnection 與 Apache 的 HttpClient。兩者都能處理 GET 與 POST 請求,但使用方式略有不同。

HttpURLConnection 基本用法

使用 GET 請求時,可先建立 URL 物件,再開啟連線並讀取輸入流。

URL url = new URL("https://www.xxx.com/index.jsp");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine;
while ((inputLine = buffer.readLine()) != null) {
    resultData += inputLine;
}
in.close();
urlConn.disconnect();

使用 POST 傳送參數

URL url = new URL("https://www.xxx.com/getUser.jsp");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.connect();

DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
String content = "name=" + URLEncoder.encode("張三", "UTF-8");
out.writeBytes(content);
out.flush();
out.close();

HttpClient GET 請求

HttpGet httpRequest = new HttpGet("https://www.xxx.com/getUser.jsp");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    String strResult = EntityUtils.toString(httpResponse.getEntity());
}

HttpClient POST 請求

HttpPost httpRequest = new HttpPost("https://www.xxx.com/getUser.jsp");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userId", "123"));
HttpEntity httpentity = new UrlEncodedFormEntity(params, "UTF-8");
httpRequest.setEntity(httpentity);

HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);

實務上,網路請求應避免在主執行緒執行,並妥善處理例外、逾時與資源釋放。

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