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

OkHttp 檔案上傳與下載進度回調實作:CoreProgress 封裝全解析

編輯:關於 Android 程式設計

OkHttp 幾乎不需要再自我介紹了,Square 出品,優點多到懶得細數。但優秀的框架也有一個副作用:它把太多細節封裝得太「完美」,以至於你想插入一點自己的邏輯時,會發現無處下手。

簡單的 GET/POST 當然毫無障礙。可一旦需求變成「檔案上傳/下載,並且要把進度即時呈現給使用者」,事情就有意思了:上傳前要提示、上傳中要顯示百分比、完成後要告知結果。你去搜尋,會發現中文資料幾乎找不到答案,但換成英文搜尋,Stack Overflow 的討論串和 GitHub 上的 issue 立刻鋪滿螢幕——可見撞牆的人不只你一個。

翻過幾個靠譜的回答後,我把方案整理成一個可重複使用的擴充庫,取名 CoreProgress。核心思路只有一句:用裝飾器模式包裝 RequestBody 與 ResponseBody,在資料流動的那一刻攔截位元組數。

進度監聽的基石:Okio 的 Source 與 Sink

OkHttp 底層的 I/O 由 Okio 承載,兩個關鍵抽象是 Source(讀)與 Sink(寫)。下載對應 Source,上傳對應 Sink,我們要做的就是在這兩個資料流的讀寫過程中做統計並回呼。

下載進度:包裝 ResponseBody

先定義回呼介面:

public interface ProgressResponseListener {
    void onResponseProgress(long bytesRead, long contentLength, boolean done);
}

接著用 ForwardingSource 包裝原始的 Source,在 read 時累加位元組數:

public class ProgressResponseBody extends ResponseBody {
    private final ResponseBody responseBody;
    private final ProgressResponseListener progressListener;
    private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, ProgressResponseListener progressListener) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
    }

    @Override public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override public long contentLength() throws IOException {
        return responseBody.contentLength();
    }

    @Override public BufferedSource source() throws IOException {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // 讀到盡頭時 bytesRead 會返回 -1
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                progressListener.onResponseProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }
}

邏輯很直白:我們保留原始 ResponseBody 的引用,重寫 contentType()、contentLength() 直接轉呼原物件;而在 source() 被呼叫時,回傳的是我們包裝過的 Source。每一次 read,都把累計位元組數透過介面回呼出去。

上傳進度:包裝 RequestBody

上傳是完全對稱的問題:繼承 RequestBody,改用 ForwardingSink,在 write 時累加。

public interface ProgressRequestListener {
    void onRequestProgress(long bytesWritten, long contentLength, boolean done);
}
public class ProgressRequestBody extends RequestBody {
    private final RequestBody requestBody;
    private final ProgressRequestListener progressListener;
    private BufferedSink bufferedSink;

    public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
        this.requestBody = requestBody;
        this.progressListener = progressListener;
    }

    @Override public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override public long contentLength() throws IOException {
        return requestBody.contentLength();
    }

    @Override public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        requestBody.writeTo(bufferedSink);
        bufferedSink.flush(); // 必須 flush,否則最後一段資料可能不會送出
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            long bytesWritten = 0L;
            long contentLength = 0L;

            @Override public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0) {
                    contentLength = contentLength(); // 只取一次,避免重複計算
                }
                bytesWritten += byteCount;
                progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
            }
        };
    }
}

怎麼用?Helper 才是關鍵

上傳很簡單:把原始 RequestBody 和監聽器丟給 Helper,拿回包裝後的物件丟進請求即可。下載則麻煩一些——OkHttp 回傳的是 Response,我們得用攔截器(Interceptor)把包裝後的 ResponseBody 塞回去。為了汙染原有的 OkHttpClient 實例,這裡用 clone() 複製一份再掛攔截器。

public class ProgressHelper {

    /** 複製一份 Client 並掛上下載進度攔截器 */
    public static OkHttpClient addProgressResponseListener(OkHttpClient client,
                                                           final ProgressResponseListener progressListener) {
        OkHttpClient clone = client.clone();
        clone.networkInterceptors().add(new Interceptor() {
            @Override public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                        .build();
            }
        });
        return clone;
    }

    /** 直接包裝請求體,用於上傳 */
    public static ProgressRequestBody addProgressRequestListener(RequestBody requestBody,
                                                               ProgressRequestListener progressRequestListener) {
        return new ProgressRequestBody(requestBody, progressRequestListener);
    }
}

把進度送回主執行緒

還有一個容易忽略的前提:OkHttp 的所有回呼都發生在背景執行緒,而進度條只能由主執行緒更新。因此我們需要一層 UI 介面的包裝。

由於要走訊息機制,先把三個參數(當前位元組、總長度、是否完成)封裝成實體類,方便透過 Message 傳遞:

public class ProgressModel implements Serializable {
    private long currentBytes;
    private long contentLength;
    private boolean done;

    public ProgressModel(long currentBytes, long contentLength, boolean done) {
        this.currentBytes = currentBytes;
        this.contentLength = contentLength;
        this.done = done;
    }
    // getter / setter / toString 略
}

接著用抽象類實作 UI 層回呼。這裡有兩個細節值得注意:內部 Handler 對外部監聽器持有的是弱引用,避免 Activity 被銷毀後仍被訊息佇列引用而無法回收;建構時傳入 Looper.getMainLooper(),確保 handleMessage 在主執行緒執行。

public abstract class UIProgressRequestListener implements ProgressRequestListener {
    private static final int REQUEST_UPDATE = 0x01;

    private static class UIHandler extends Handler {
        private final WeakReference mWeakRef;

        public UIHandler(Looper looper, UIProgressRequestListener listener) {
            super(looper);
            mWeakRef = new WeakReference(listener);
        }

        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUEST_UPDATE:
                    UIProgressRequestListener listener = mWeakRef.get();
                    if (listener != null) {
                        ProgressModel model = (ProgressModel) msg.obj;
                        listener.onUIRequestProgress(model.getCurrentBytes(),
                                model.getContentLength(), model.isDone());
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }

    private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);

    @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
        Message message = Message.obtain();
        message.obj = new ProgressModel(bytesWritten, contentLength, done);
        message.what = REQUEST_UPDATE;
        mHandler.sendMessage(message);
    }

    /** 在這個方法裡更新 UI */
    public abstract void onUIRequestProgress(long bytesWritten, long contentLength, boolean done);
}

UIProgressResponseListener 的實作幾乎一模一樣,只是把介面換成 ProgressResponseListener、把抽象方法換成 onUIResponseProgress。

接入方式

為了方便 Android Studio 使用者,這個庫已發佈到中央倉庫,加入依賴即可:

dependencies {
    compile 'cn.edu.zafu:coreprogress:0.0.1'
}

注意:OkHttp 本身的依賴需要自行加入,這個庫只把它當成編譯期依賴,並沒有打包進去。

呼叫範例

版面配置放兩個進度條與兩個按鈕:

// 下載
final UIProgressResponseListener listener = new UIProgressResponseListener() {
    @Override public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
        if (contentLength != -1) {
            downloadProgress.setProgress((int) ((100 * bytesRead) / contentLength));
        }
    }
};
Request request = new Request.Builder().url("https://example.com/test/1.doc").build();
ProgressHelper.addProgressResponseListener(client, listener)
        .newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Request request, IOException e) { /* 失敗處理 */ }
            @Override public void onResponse(Response response) throws IOException { /* 完成處理 */ }
        });
// 上傳
File file = new File("/sdcard/1.doc");
final UIProgressRequestListener listener = new UIProgressRequestListener() {
    @Override public void onUIRequestProgress(long bytesWrite, long contentLength, boolean done) {
        if (contentLength != 0) {
            uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
        }
    }
};
RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM)
        .addFormDataPart("hello", "android")
        .addFormDataPart("photo", file.getName(), RequestBody.create(null, file))
        .build();
Request request = new Request.Builder().url("https://example.com/test/result.php")
        .post(ProgressHelper.addProgressRequestListener(body, listener))
        .build();
client.newCall(request).enqueue(new Callback() { /* onFailure / onResponse */ });

三個實務上的坑

第一,contentLength 可能是 -1。當伺服器沒有回傳長度資訊時,它會一直是 -1,此時無法用百分比呈現,只能改用 done 判斷是否結束。兩者結合判斷,是最穩妥的寫法。

第二,別忘記設定逾時。讀寫大檔案時,若未調整 connectTimeout、readTimeout、writeTimeout,很容易在傳輸中途拋出異常。實際值請依檔案大小與網路環境設定,不要照抄別人的誇張數值。

第三,最終結果仍舊回到 OkHttp 的 Callback。成功走 onResponse,失敗走 onFailure,進度監聽只是過程呈現,「上傳完成」「下載失敗請重試」這類收尾提示應該寫在那裡。

伺服器端要做的其實很少:接收 POST 內容與檔案資訊,把上傳的檔案存到指定目錄,然後回一個狀態即可。剩下的,交給進度條去說服使用者耐心等待。

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