Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 網路圖片抓取:HttpURLConnection 與位元組串流

要把網路上的圖片顯示在自己的應用裡,Android 提供的做法是把流程拆成兩層:一層負責「把 URL 變成位元組」,另一層負責「把位元組變成圖片並顯示」。這樣切開的好處是網路邏輯可以獨立測試與複用,UI 端只管畫面。

一、版面配置

畫面上放提示文字、一個輸入網址的欄位、一個抓取按鈕,以及用來顯示結果的 ImageView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/request" />

    <EditText
        android:id="@+id/imageaddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/getimagebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/getimage" />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

二、字串資源

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="request">網路獲取圖片</string>
    <string name="app_name">網絡獲取圖片數據</string>
    <string name="getimage">得到圖片</string>
    <string name="requestout">請求超時</string>
</resources>

requestout 是預留給超時提示用的,對應下面業務層設定的連線逾時。

三、業務層:把 URL 讀成位元組陣列

package sn.len.service;

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

import sn.len.util.ImageByte;

public class GetImageService {

    public static byte[] imageByte(String path) throws IOException {
        URL url = new URL(path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(5 * 1000);
        InputStream inStream = con.getInputStream();
        byte imageData[] = ImageByte.getBtye(inStream);
        return imageData;
    }
}

這裡有兩個實務上必須補上的收尾動作:讀完串流後要關閉 inStream,並呼叫 con.disconnect() 釋放連線,否則反覆抓取會累積資源。另外 setConnectTimeout(5 * 1000) 的意義是連線最多等五秒,對應的就是 requestout 那個提示;若還想控制讀取階段的等待,可再設定 setReadTimeout()。

四、工具層:串流轉位元組

package sn.len.util;

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

public class ImageByte {

    public static byte[] getBtye(InputStream inStream) throws IOException {
        byte b[] = new byte[1024];
        ByteArrayOutputStream byteoutstream = new ByteArrayOutputStream();
        int len = 0;
        while ((len = inStream.read(b)) != -1) {
            byteoutstream.write(b, 0, len);
        }
        return byteoutstream.toByteArray();
    }
}

這是最典型的串流複製寫法:準備一個 1KB 的緩衝區反覆讀取,每次把實際讀到的 len 個位元組寫進 ByteArrayOutputStream,最後一次 toByteArray() 取出完整內容。注意寫入時用的是 len 而非陣列全長,否則結尾會帶入多餘的零值。

五、串起 UI 與服務

Activity 端要做的事:為按鈕掛監聽、取出輸入框的網址、呼叫 GetImageService.imageByte() 取得位元組,再用 BitmapFactory.decodeByteArray() 解成 Bitmap,最後交給 ImageView.setImageBitmap() 顯示。

這裡有一個不能忽略的限制:網路請求不可在主執行緒(UI 執行緒)進行,否則會直接拋出 NetworkOnMainThreadException。正確做法是把抓取放到背景執行緒(AsyncTask 或自建 Thread + Handler),完成後再切回主執行緒更新 ImageView。同時別忘了在 AndroidManifest.xml 加上網路權限:

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

把「抓資料」與「顯示資料」分開、把網路移出主執行緒、加上權限宣告——這三件事做對,圖片抓取就沒有祕密了。

Copyright © Linux教程網 All Rights Reserved