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

Android 使用 HttpURLConnection 發送 POST 請求

編輯:關於 Android 程式設計

在 Android 中發送 HTTP POST 請求,可使用 HttpURLConnection。重點是將請求放到子執行緒,並正確寫入輸出流、讀取回應。

URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(packetData.length);
conn.setUseCaches(false);

OutputStream os = conn.getOutputStream();
int offset = 0;
int len = READ_WRITE_SIZE;
while (offset != packetData.length) {
  if (offset + len > packetData.length) {
    len = packetData.length - offset;
  }
  os.write(packetData, offset, len);
  os.flush();
  offset = offset + len;
}

InputStream fin = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
  total.append(line);
}
textView.setText(total.toString());

注意:不要在主執行緒執行網路請求,否則可能觸發 NetworkOnMainThreadException。實務上可用 Thread、ExecutorService 或其他非同步機制。

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