編輯:關於 Android 程式設計
網路請求是所有 App 的基礎能力。在 Retrofit、OkHttp 普及之前,HttpURLConnection 是唯一的標準選擇,而它至今仍是理解 HTTP 溝通細節最好的教材——因為所有環節都得自己來:開連線、寫入 body、讀取串流、切回主執行緒。本文以一個登入表單為例完整走一遍。
NetworkOnMainThreadException 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));
}
}
}
<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" />
作為教學範例它夠清楚了,但實際專案有幾個必須修正的地方:
參數要做 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 細節的完全掌控,適合學習與特殊需求,但序列化、錯誤處理、重試機制、連線池若全靠自己實作,成本遠高於引入成熟套件。
Android 使用 OpenCV:非 Cygwin 方式的編譯環境搭建(Win7 + Eclipse + ADT + CDT + NDK)
整個配置其實只有簡單的三步,官方文檔寫得非常簡明全面,值得稱道。 【準備】 1. Eclipse(Indigo) 2. ADT:就是給 Eclipse 添加 Andro
【Android】GreenDao ORM 框架深入實戰:關聯關係與自訂屬性轉換器
上一篇我們介紹了 GreenDao 的基本用法,如果你還不熟悉,建議先讀完前一篇再來看這篇,學習效果會更好。今天我們要繼續深入 GreenDao 的 relation 部
Android 學習筆記:ListView 的簡單使用
(1)佈局檔中加入一個 ListView: (2)在 MainActivity 中設定選擇模式、綁定 ArrayAdapter,並處理項目的點擊事件:package
RxJava2 核心變化全解析
最近剛把 RxJava1.x 的源碼讀完,正好 RxJava2.x 也放出了 RC 版本。趁著正式版發布前的空檔,本文就來對 RxJava2.x 做一次入門級的剖析。