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

Android 實現地址欄輸入網址並抓取網頁源碼的完整流程

編輯:關於 Android 程式設計

本範例做一個極簡版的瀏覽器雛形:上方一個輸入框與一個按鈕,下方用可滾動的文字區顯示該網址回傳的 HTML 原始碼。整個流程涵蓋了版面配置、子執行緒網路請求、Handler 更新 UI、編碼判斷與網路狀態檢查,是相當完整的 Networking 入門練習。

一、版面配置

<EditText
    android:id="@+id/et_url"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:ems="10"
    android:text="@string/url_text" >
    <requestFocus />
</EditText>

<Button
    android:id="@+id/btn_ie"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/et_url"
    android:onClick="sendHttp"
    android:text="@string/btn_text" />

<ScrollView
    android:id="@+id/sv_id"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/btn_ie" >
    <TextView
        android:id="@+id/tv_ie"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/ie_text" />
</ScrollView>

用 ScrollView 包住 TextView 是必要的,因為網頁源碼往往遠超一屏高度。

strings.xml 中的文字資源:

<string name="url_text">https://luochuang.iteye.com/blog/1606231</string>
<string name="btn_text">瀏覽</string>
<string name="ie_text">顯示瀏覽網頁內容</string>

二、MainActivity

public class MainActivity extends Activity {
    public EditText et_url;
    public TextView tv_ie;
    public NetWorkUtils netWorkUtils;
    private Handler handler;
    public String content;
    public static final int TEXT = 1;

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

        et_url = (EditText) findViewById(R.id.et_url);
        tv_ie = (TextView) findViewById(R.id.tv_ie);
        netWorkUtils = new NetWorkUtils(this);

        handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case TEXT:
                        tv_ie.setText(content);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    public void sendHttp(View v) {
        // 先確認網路可用,再啟動子執行緒
        boolean flag = netWorkUtils.setActiveNetWork();
        if (flag) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    send();
                    handler.sendEmptyMessage(TEXT);
                }
            }).start();
        }
    }

    public void send() {
        String path = et_url.getText().toString();
        if (path.isEmpty()) {
            Toast.makeText(MainActivity.this, "訪問的 url 地址不能為空",
                    Toast.LENGTH_LONG).show();
        } else {
            content = HttpUtils.sendGet(path);
        }
    }
}

三、HTTP 工具類

public class HttpUtils {
    public static String sendGet(String path) {
        String content = null;
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection =
                    (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);

            if (httpURLConnection.getResponseCode() == 200) {
                InputStream is = httpURLConnection.getInputStream();
                byte data[] = StreamTools.isToData(is);
                content = new String(data);
                // 依內容自行判斷編碼
                if (content.contains("gb2312")) {
                    content = new String(data, "gb2312");
                }
            }
            httpURLConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}

讀流的部分抽成獨立工具,方便日後 reuse:

public class StreamTools {
    public static byte[] isToData(InputStream is) throws IOException {
        ByteArrayOutputStream bops = new ByteArrayOutputStream();
        byte buffer[] = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            bops.write(buffer, 0, len);
        }
        return bops.toByteArray();
    }
}

四、網路狀態檢查

public class NetWorkUtils {
    private Context context;
    public ConnectivityManager connectivityManager;

    public NetWorkUtils(Context context) {
        this.context = context;
        connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public boolean setActiveNetWork() {
        boolean flag = false;
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            new AlertDialog.Builder(context)
                .setTitle("網絡不可用")
                .setMessage("可以設置網絡?")
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 直接跳去系統設定頁
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_MAIN);
                        intent.addCategory("android.intent.category.LAUNCHER");
                        intent.setComponent(new ComponentName(
                                "com.android.settings",
                                "com.android.settings.Settings"));
                        intent.setFlags(0x10200000);
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) { }
                })
                .show();
        }
        if (networkInfo != null) {
            flag = true;
        }
        return flag;
    }
}

偵測不到網路時不該直接失敗,而是詢問使用者是否前往設定開啟——這是很基本但常被忽略的體感細節。實務上更常用 Settings.ACTION_WIRELESS_SETTINGS 這個明確的 action 來開啟網路設定頁,比指定 ComponentName 更能相容不同 ROM。

五、權限宣告

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

兩者缺一不可:INTERNET 讓你能連線,ACCESS_NETWORK_STATE 讓你能查詢連線狀態。

六、幾點改進建議

這份程式碼的結構清楚,適合當入門範例,但實際上線前建議調整:

  • 編碼判斷太粗糙。用 content.contains("gb2312") 猜編碼不可靠,應優先讀取回應標頭的 Content-Type charset,再回退到解析 meta 標籤。
  • 主執行緒外的 Toast。send() 是在子執行緒中跑的,裡面直接跳 Toast 在部分版本會出問題,應統一透過 Handler 回到主執行緒處理。
  • 缺少讀取逾時。只設了連線逾時,建議補上 setReadTimeout()。
  • Activity 銷毀時的處理。執行緒與 Handler 應在 onDestroy 中妥善收尾,避免記憶體洩漏。
  • 正規做法。若要真正顯示網頁,應該用 WebView 而非抓源碼塞進 TextView;若只是要資料,則 HTTP 用戶端建議改用 OkHttp 或 Retrofit。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved