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

Android 進階:使用 HttpURLConnection 下載網頁源碼

編輯:關於 Android 程式設計

延續上一篇介紹的圖片下載與顯示,本文說明如何根據網址取得網頁的原始碼。其實取得網頁源碼比圖片下載更簡單,只需對既有程式碼稍作修改即可。

public class OtherActivity extends Activity {
    private TextView tv;
    private static final int LOAD_SUCCESS = 1;
    private static final int LOAD_ERROR = -1;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOAD_SUCCESS:
                    tv.setText((String) msg.obj);
                    break;
                case LOAD_ERROR:
                    Toast.makeText(getApplicationContext(), "加載失敗", 0).show();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
    }
    // Button 的點擊事件
    public void show(View view) {
        new Thread(new Runnable() {
            public void run() { getHttp(); }
        }).start();
    }
    // 下載網頁源碼的主方法
    private void getHttp() {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            url = new URL("https://www.baidu.com");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);      // 設定超時 5 秒
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                byteArrayOutputStream = new ByteArrayOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                byteArrayOutputStream.flush();
                byte[] arr = byteArrayOutputStream.toByteArray();
                Message msg = handler.obtainMessage();
                msg.what = LOAD_SUCCESS;
                msg.obj = new String(arr);
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            handler.sendEmptyMessage(LOAD_ERROR);
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
                if (byteArrayOutputStream != null) byteArrayOutputStream.close();
            } catch (Exception e) {
                handler.sendEmptyMessage(LOAD_ERROR);
                e.printStackTrace();
            }
        }
    }
}

布局檔:

<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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:onClick="show"
        android:text="顯示" />
    <TextView android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

權限:

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

重點在於將網路請求放在子執行緒中執行,並透過 Handler 將結果回傳主執行緒更新 UI,避免阻塞。

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