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

Android POST 請求實作教學:HttpURLConnection 搭配 Handler 回傳結果

編輯:關於 Android 程式設計

網路請求是所有 App 的基礎能力。在 Retrofit、OkHttp 普及之前,HttpURLConnection 是唯一的標準選擇,而它至今仍是理解 HTTP 溝通細節最好的教材——因為所有環節都得自己來:開連線、寫入 body、讀取串流、切回主執行緒。本文以一個登入表單為例完整走一遍。

三個關鍵觀念

  1. 網路操作必須在子執行緒。 Android 3.0 之後,主執行緒禁止網路連線,違者直接拋 NetworkOnMainThreadException
  2. 結果必須透過 Handler 送回主執行緒。 只有主執行緒能更新 UI
  3. POST 的參數放在 request body,不是網址後面。 這與 GET 有本質差異

MainActivity.java

 package com.tsh.test;

 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.PrintWriter;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity extends Activity {

     public Button loginBtn;
     public TextView loginUserName;
     public TextView loginPassword;
     public static String API = "https://mail.sina.net/loginxxx";
     public LoginHandler loginHandler;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         loginBtn = (Button) findViewById(R.id.loginBtn);
         loginUserName = (TextView) findViewById(R.id.loginUsername);
         loginPassword = (TextView) findViewById(R.id.loginPassword);

         loginBtn.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View v) {
                 // 網路請求不可在主執行緒執行,另開執行緒
                 new Thread(new LoginRunable()).start();
             }
         });

         loginHandler = new LoginHandler();
     }

     /** 在子執行緒中完成整段 HTTP 溝通 */
     class LoginRunable implements Runnable {
         @Override
         public void run() {
             HttpURLConnection http = null;
             try {
                 URL url = new URL(API);
                 http = (HttpURLConnection) url.openConnection();
                 http.setRequestMethod("POST");
                 http.setDoInput(true);
                 http.setDoOutput(true);
                 // 以 form-urlencoded 方式送出參數
                 OutputStream ops = http.getOutputStream();
                 PrintWriter pw = new PrintWriter(ops);
                 String username = loginUserName.getText().toString();
                 String password = loginPassword.getText().toString();
                 pw.write("email=" + username + "&psw=" + password
                         + "&loginfrom=app&output=json");
                 pw.flush();

                 // 讀取伺服器回應
                 InputStream ins = http.getInputStream();
                 byte[] buffer = new byte[1024];
                 int length;
                 StringBuilder sb = new StringBuilder();
                 while ((length = ins.read(buffer)) != -1) {
                     sb.append(new String(buffer, 0, length));
                 }

                 // 包裝成 Message 交給 Handler
                 Message msg = new Message();
                 msg.what = 1;
                 msg.obj = sb.toString();
                 loginHandler.sendMessage(msg);
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 if (http != null) {
                     http.disconnect(); // 記得釋放連線
                 }
             }
         }
     }

     /** 回到主執行緒處理 UI */
     class LoginHandler extends Handler {
         @Override
         public void handleMessage(Message msg) {
             String loginResponse = (String) msg.obj;
             Toast.makeText(MainActivity.this, loginResponse, Toast.LENGTH_SHORT).show();
             // 登入成功後可在此跳轉
             // startActivity(new Intent(MainActivity.this, MailIndexActivity.class));
         }
     }
 } 

activity_main.xml

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical">

     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="用戶名" />

     <EditText
         android:id="@+id/loginUsername"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:hint="請輸入用戶名" />

     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="密碼" />

     <EditText
         android:id="@+id/loginPassword"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:hint="請輸入密碼"
         android:inputType="textPassword" />

     <Button
         android:id="@+id/loginBtn"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="登陸認證" />
 </LinearLayout> 

別忘了網路權限

少了這一行,連線會在建立階段就被系統攔下,且不會有任何明顯錯誤訊息:

 <uses-permission android:name="android.permission.INTERNET" /> 

這份程式碼上 production 之前該改什麼

作為教學範例它夠清楚了,但實際專案有幾個必須修正的地方:

參數要做 URL 編碼。 直接字串拼接時,若密碼含有 &、=、空白或中文,會讓伺服器解析錯誤甚至造成參數注入。應改用 URLEncoder.encode(value, "UTF-8") 逐一編碼。

不要取用明文密碼。 範例直接從 loginPassword.getText().toString() 取值,實際上應在取得後立刻清除,且傳輸務必走 HTTPS。

要處理 HTTP 狀態碼。 目前不管伺服器回 200 還是 500,程式都照讀 body。應先檢查 getResponseCode(),非 2xx 時改讀 getErrorStream() 取得錯誤訊息。

要處理逾時與失敗。 網路環境不可控,應設定 setConnectTimeout() 與 setReadTimeout(),並在例外時透過 Handler 回報失敗狀態給 UI,否則使用者只會看到「按了沒反應」。

Handler 有記憶體洩漏風險。 內部類別 Handler 會隱式持有 Activity 參考,若請求耗时過長而使用者已離開頁面,就會無法回收。建議改為 static 內部類別搭配 WeakReference,或直接使用 runOnUiThread()。

最後,若你在撰寫新專案,請直接採用 Retrofit + Gson 或 Ktor / OkHttp + Coroutines。上面這套寫法保留了對 HTTP 細節的完全掌控,適合學習與特殊需求,但序列化、錯誤處理、重試機制、連線池若全靠自己實作,成本遠高於引入成熟套件。

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