編輯:關於 Android 程式設計
這一章的目標很明確:讓 App 能透過 HTTP 與伺服器對話,並把回傳的資料解析成可用的內容。這是 Android 裡最基礎也最常用的一塊網路能力,我們從 WebView 開始,一路走到兩種 HTTP 客戶端的實作。
有了 WebView,你就能在自己的應用裡放一個瀏覽器,用極低的成本呈現各種網頁。用法本身也不難,我們直接看例子。建立一個 WebViewTest 專案,先改寫 activity_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
這裡出現了一個新控制項 WebView,它專門用來顯示網頁。設定了一個 id,並讓它填滿整個螢幕。
接著改 MainActivity:
public class MainActivity extends Activity {
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.web_view);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 頁面跳轉時仍在同一個 WebView 中載入
view.loadUrl(url);
// 回傳 true 表示由當前 WebView 自行處理,不叫起系統瀏覽器
return true;
}
});
webview.loadUrl("https://www.baidu.com");
}
}
程式碼很短,重點有三處。先用 findViewById 拿到 WebView 實例,再透過 getSettings() 調整瀏覽器屬性——這裡只示範了 setJavaScriptEnabled(),讓 WebView 能執行 JavaScript。
再來是最關鍵的一段:呼叫 setWebViewClient() 並覆寫 shouldOverrideUrlLoading()。它的意義是,當頁面需要跳到另一個網頁時,我們希望目標頁仍然留在當前 WebView 裡顯示,而不是跳出系統瀏覽器。
最後一行 loadUrl() 把網址傳進去就完成了。
還有一件事別忘記:這個程式要用到網路,而存取網路必須先聲明權限,所以得改 AndroidManifest.xml:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="com.example.webviewtest">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>

HTTP 的運作方式非常單純:客戶端送出一個請求,伺服器回一批資料,客戶端再把資料解析處理掉,就這麼簡單。
在 Android 上發送 HTTP 請求,傳統上有兩條路:HttpURLConnection 與 HttpClient。先看前者。
取得實例的寫法很固定:new 一個 URL 物件並帶入目標位址,再呼叫 openConnection():
URL url = new URL("https://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
接著指定請求方法,最常見的是 GET 與 POST:GET 用來向伺服器取資料,POST 用來把資料送上去。
connection.setRequestMethod("GET");
然後就可以做一些自訂設定,例如連線與讀取逾時的毫秒數、要帶的請求標頭等,這部分依實際需求撰寫:
connection.setConnectTimeout(8000); connection.setReadTimeout(8000);
設定完成後,呼叫 getInputStream() 就能拿到伺服器回傳的輸入流,剩下的就是把內容讀出來:
InputStream in = connection.getInputStream();
用完記得關掉連線:
connection.disconnect();
新建 NetworkTest 專案,先改寫 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">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
這裡多了一個新控制項 ScrollView。手機螢幕空間有限,內容一多就顯示不完,ScrollView 讓使用者可以用捲動的方式看到螢幕外的部分。另外還有一顆 Button 負責送出請求,一個 TextView 負責顯示結果。
再來改 MainActivity:
public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button sendRequest;
private TextView responseText;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 只有在這裡才能安全地操作 UI
responseText.setText(response);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
// 網路請求必須放在子線程
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
流程是這樣的:按下 Send Request 後進入 sendRequestWithHttpURLConnection(),先開一條子線程,在裡面用 HttpURLConnection 向百度首頁發出請求,再用 BufferedReader 把回傳的串流讀完,裝進一個 Message 物件。
為什麼要用 Message?因為子線程不能碰 UI。我們希望把結果顯示到畫面上,所以建立 Message 並用 Handler 送出,之後在 handleMessage() 裡取出字串設定給 TextView。
執行前同樣要在 AndroidManifest.xml 加上網路權限:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="com.example.networktest">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
執行後按下按鈕,畫面上就會出現伺服器回傳的內容:

回傳的是 HTML 格式,當然伺服器也可以改成回傳 JSON。
做法也不繞:把請求方法改成 POST,並在讀取輸入流之前把要送出的資料寫出去。注意每筆資料都是鍵值對,彼此以 & 分隔。例如要送使用者名稱與密碼:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
HttpClient 是 Apache 提供的 HTTP 存取介面,從早期就被納入 Android API。它能做到的效果和 HttpURLConnection 幾乎一樣,但寫法差別不小,值得一學。
首先要知道它是個介面,不能直接 new,實務上會建立 DefaultHttpClient 實例:
HttpClient httpClient = new DefaultHttpClient();
要發 GET 請求,就建立一個 HttpGet 並帶入位址,然後交給 execute():
HttpGet httpGet = new HttpGet("https://www.baidu.com");
httpClient.execute(httpGet);
要發 POST 請求,則建立 HttpPost:
HttpPost httpPost = new HttpPost("https://www.baidu.com");
接著用一個 NameValuePair 集合盛裝待送出的參數,包裝成 UrlEncodedFormEntity,再透過 setEntity() 掛上去:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
之後同樣交給 execute() 執行:
httpClient.execute(httpPost);
execute() 會回傳一個 HttpResponse,伺服器的所有回應都在裡面。通常我們先看狀態碼,等於 200 才代表請求與回應都成功:
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 請求與回應皆成功
}
接著在這個判斷裡取出內容:先用 getEntity() 取得 HttpEntity,再用 EntityUtils.toString() 轉成字串:
HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity);
要注意的是,如果伺服器回傳的內容含中文,直接轉換容易出現亂碼,這時把字元集指定為 utf-8 即可:
String response = EntityUtils.toString(entity, "utf-8");
基本概念就這些,接著把 NetworkTest 改用 HttpClient 重寫一次。版面完全不用動,只改 MainActivity:
public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button sendRequest;
private TextView responseText;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == SHOW_RESPONSE) {
responseText.setText((String) msg.obj);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpClient();
}
}
private void sendRequestWithHttpClient() {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
兩種寫法各有擁護者:HttpURLConnection 更貼近原生、可控性高;HttpClient 的 API 抽象層更完整,POST 送出參數寫起來乾淨。理解兩者的差異,比記住某一種寫法更重要——尤其在面對不同專案遺留的程式碼時。
Android 自訂 View 中 Bitmap 縮放與拖曳實作解析
實作概念在 Android 中,若要在自訂 View 上呈現可拖曳、可縮放的 Bitmap,核心思路是將觸控事件、Matrix 變換與邊界檢查結合起來。自訂 MyImag
Android 拼圖小遊戲:方塊切割、點擊與手勢操作
拼圖遊戲的整體思路拼圖遊戲可以拆解為三件事:切圖、移動、判定勝利。先把大圖切成若干小方塊,用 GridLayout 排列;再讓空白方塊與相鄰方塊交換;最後檢查每個方塊是否
Android 自定義軟鍵盤:打造屬於你的安全輸入面板
前不久項目需要一個自定義軟鍵盤,我上網翻了翻,覺得大多數方案都偏繁瑣,於是決定自己動手實現一個以備不時之需。這裡參考的是百度錢包的軟鍵盤,看著還不錯: 一、SoftIn
Android 手動控制軟鍵盤顯示與隱藏的方法
在 Android 開發中,經常會遇到這樣的需求:完成某項操作後要收起鍵盤,也就是讓螢幕上的軟鍵盤不再顯示。今天就和各位分享,如何透過程式碼來控制 Android 軟鍵盤