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

Android 開發入門:實作 HTML 原始碼查看器

編輯:關於 Android 程式設計

這是一個小而完整的網路範例:按下按鈕,抓取伺服器上的 HTML 檔,把原始碼顯示在畫面上。它涵蓋了 HttpURLConnection 連線、字串串流讀取、以及用 Handler 把結果送回主執行緒三個基本技能。

MainActivity.java

package com.itheima.htmlviewer;

import java.net.HttpURLConnection;
import java.net.URL;

import com.itheima.htmlviewer.utils.Utils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView tv = (TextView) findViewById(R.id.tv);
            tv.setText((String) msg.obj);
        }
    };

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

    public void click(View v) {
        Thread t = new Thread() {
            @Override
            public void run() {
                String path = "https://192.168.1.103:8080/1.html";
                try {
                    URL url = new URL(path);
                    // 取得連線物件,此時尚未真正建立連線
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    // 呼叫 getResponseCode() 才會真正建立連線
                    if (conn.getResponseCode() == 200) {
                        // 串流內容就是 HTML 原始碼
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);

                        // 背景執行緒不能直接更新 UI,透過 Handler 轉交
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                    }
                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}

Utils.java

package com.itheima.htmlviewer.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Utils {

    public static String getTextFromStream(InputStream is) {
        byte[] b = new byte[1024];
        int len = 0;
        // 用 ByteArrayOutputStream 一邊讀一邊寫,最後一次轉成 byte[]
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while ((len = is.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            // Android 預設編碼為 UTF-8
            // 若出現亂碼,代表伺服器與客戶端編碼不一致,需統一其中一方
            String text = new String(bos.toByteArray(), "UTF-8");
            return text;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) bos.close();
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="查看源文件" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

重點整理

連線時機。url.openConnection() 只是取得物件,並未真正連線。真正發出請求的時機是呼叫 getResponseCode()、getInputStream() 或 getContentLength() 等需要回應的時刻。理解這點才能正確安排程式流程。

逾時設定是必要的。不設 setConnectTimeout 與 setReadTimeout,遇到伺服器無回應時會無限期卡住,是 ANR 的常見成因。

網路必須在子執行緒。Android 3.0 之後,主執行緒進行網路作業會直接拋出 NetworkOnMainThreadException。範例用 Thread + Handler 解決;實務上 Kotlin 可用協程 + withContext(Dispatchers.IO),Java 可用 ExecutorService 搭配 runOnUiThread 或 LiveData。

權限。記得在清單檔加入 <uses-permission android:name="android.permission.INTERNET" />。另外 Android 9.0 起預設禁止明文 HTTP,需要改用 HTTPS,或在 res/xml/network_security_config.xml 中明確開放 cleartextTrafficPermitted(僅限開發階段使用)。

編碼問題怎麼處理。亂碼的本質是兩端編碼不一致。解法有二:一是在客戶端明確指定編碼(如範例的 new String(bytes, "UTF-8")),二是修改伺服器端輸出編碼。若回應標頭有帶 Content-Type: text/html; charset=utf-8,最穩妥的做法是從標頭讀出 charset 再用。

串流與資源的收尾。InputStream 與 ByteArrayOutputStream 都應在 finally 中關閉,避免連線佔用。用 try-with-resources 更乾淨。

延伸思考

這個範例最有價值的地方,是它把「HTTP 讀回來的串流如何變成畫面上的內容」這條路走清楚了。不論是文字查看器還是圖片查看器,差別只在最後一哩:

  • 文字:串流 → ByteArrayOutputStream → String → TextView.setText()
  • 圖片:串流 → BitmapFactory.decodeStream() → Bitmap → ImageView.setImageBitmap()

中間的網路溝通、執行緒切換、錯誤處理邏輯幾乎一模一樣。把這條路想通,之後不管是載入 JSON、下載檔案還是顯示縮圖,都能自行變化出來。

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