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

Android HttpURLConnection 發送請求

編輯:關於 Android 程式設計

使用 HttpURLConnection

在 Android 中,HttpURLConnection 是常見的網路請求方式。以下示範送出 POST 請求並讀取伺服器回應。

URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);

送出參數

PrintWriter writer = new PrintWriter(connection.getOutputStream());
writer.print("content=" + params[0]);
writer.flush();
writer.close();

讀取回應

InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int ch;
while ((ch = input.read()) != -1) {
    buffer.write(ch);
}
String result = buffer.toString();

搭配非同步任務

網路請求不可在 UI 執行緒直接執行,通常會搭配 AsyncTask、Thread 或其他背景任務機制。完成後再更新介面。

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