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

Android 網路開發:實作一個網頁原始碼查看器(HttpURLConnection + Handler)

編輯:關於 Android 開發

Android 網路開發:實作一個網頁原始碼查看器(HttpURLConnection + Handler)

本文示範如何打造一個簡易的網頁原始碼查看器:使用者輸入網址後,App 在背景擷取該網頁的 HTML 原始碼,並顯示在畫面上。

一、XML 布局設計

<?xml version="1.0"?>
<LinearLayout
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:android="https://schemas.android.com/apk/res/android"
    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" >

    <EditText
        android:id="@+id/et_url"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="https://www.baidu.com" />

    <Button
        android:id="@+id/bt_looksource"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查看源碼" />

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

布局中主要用到了三個控制項:輸入網址的 EditText、觸發查詢的 Button,以及用來顯示原始碼的 TextView(外層用 ScrollView 包裹以便捲動)。

二、MainActivity 程式碼

package com.itheima.sourcelook;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private EditText et_url;
    private TextView tv_source;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        et_url = (EditText) findViewById(R.id.et_url);
        Button bt_looksource = (Button) findViewById(R.id.bt_looksource);
        tv_source = (TextView) findViewById(R.id.tv_source);

        // 二、設定點擊事件
        bt_looksource.setOnClickListener(this);
        System.out.println("oncreate 方法線程:" + Thread.currentThread().getName());
    }

    // ☆☆☆1. 在主線程中建立一個 Handler 物件
    private Handler handler = new Handler() {
        // ☆☆☆2. 重寫 handleMessage 方法,用來接收子線程中發來的消息
        public void handleMessage(android.os.Message msg) {
            // ☆☆☆5. 接收子線程發送的資料並處理
            String result = (String) msg.obj;
            // ☆☆☆6. 當前方法屬於主線程,可以進行 UI 更新
            // 五、把伺服器返回的內容顯示到 TextView 上
            tv_source.setText(result);
        };
    };

    @Override
    public void onClick(View v) {
        try {
            // 三、在 onClick 中取得使用者輸入的 url
            final String url_str = et_url.getText().toString().trim();
            if (TextUtils.isEmpty(url_str)) {
                Toast.makeText(mContext, "url 不能為空", 0).show();
                return;
            }
            System.out.println("oclick 方法線程:" + Thread.currentThread().getName());

            // 建立一個子線程做網路請求
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("runnable 線程:" + Thread.currentThread().getName());
                        // 四、請求 url 位址
                        // 1. 建立一個 URL 物件
                        URL url = new URL(url_str);
                        // 2. 取得一個 URLConnection 物件
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        // 3. 為 connection 設定請求參數、請求方式與連線逾時
                        connection.setRequestMethod("GET");       // 設定請求方式
                        connection.setConnectTimeout(1000 * 10);  // 設定逾時時間
                        // 4. 取得資料前先判斷響應碼:
                        //    200 成功、206 部分成功、300 跳轉/重定向、400 錯誤、500 伺服器異常
                        int code = connection.getResponseCode();
                        if (code == 200) {
                            // 5. 取得有效資料,並把串流解析成 String
                            InputStream inputStream = connection.getInputStream();
                            String result = StreamUtils.streamToString(inputStream);

                            // ☆☆☆3. 子線程中建立一個 Message 物件,用來攜帶資料給主線程
                            Message msg = new Message();
                            msg.obj = result;
                            // ☆☆☆4. 用 handler 把 message 發送到主線程
                            handler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、串流轉字串的 StreamUtils 工具類別

package com.itheima.sourcelook;

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

public class StreamUtils {
    public static String streamToString(InputStream in) {
        String result = "";
        try {
            // 建立一個位元組陣列寫入串流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
                out.flush();
            }
            result = out.toString(); // 把位元組串流轉換成 string
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

這個工具類別的作用,就是把輸入串流(InputStream)逐段讀進位元組陣列,再組裝成字串(byte → String)。

老師筆記重點整理

訪問網路需要在清單檔中加入 Internet 權限:android.permission.INTERNET。

使用 HttpURLConnection 請求一個 url 並取得內容的標準流程:

// 1. 建立一個 URL 物件
URL url = new URL(url_str);
// 2. 取得一個 URLConnection 物件
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3. 設定請求參數、請求方式與連線逾時
connection.setRequestMethod("GET");       // 設定請求方式
connection.setConnectTimeout(1000 * 10);  // 設定逾時時間
// 4. 取得資料前先判斷響應碼
int code = connection.getResponseCode();
if (code == 200) {
    // 5. 取得有效資料並解析成 String
    InputStream inputStream = connection.getInputStream();
    String result = StreamUtils.streamToString(inputStream);
}

三個常見的注意事項:

1. ANR(Application Not Responding,應用無回應):Android 中的耗時操作(網路請求、大檔案複製、資料庫操作)必須放在子線程中執行,否則會引發 ANR。

2. Android 4.0 之後,網路操作強制要求在子線程中進行,否則會拋出 android.os.NetworkOnMainThreadException。

3. 子線程不能直接更新 UI(控制項內容),否則會拋出 ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

歸納來說:主線程不能做耗時操作,而網路請求正是耗時操作,必須放到子線程;但子線程又不能更新 UI。這看似矛盾的兩點,解決辦法就是使用 Handler——由子線程負責網路請求,再把結果透過 Handler 送回主線程更新介面。

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