如何使用 Retrofit 2 测量巨大字符串的上传进度?

How to measure upload progress of a huge String with Retrofit 2?

我使用 Retrofit 2 和 POST Rest 调用将一些数据发送到后端。我的休息界面看起来像:

void postSpecialData(String base64, Callback callback);

而我的回调是 Retrofit 接口:

  void onResponse(Call<T> call, Response<T> response);
  void onFailure(Call<T> call, Throwable t);

我终于打来电话了:

getRestCommunicator().postSpecialData(encryptedBase64, new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                toast("Response code " + response.code());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                toast("Failure REST CALL");
            }
});

encryptedBase64 变量既不是文件也不是存储在某处。 如何获取上传进度以使其在进度条上可见?

:扩展 OkHttp3 的 RequestBody 并为字符串 yourHugeString 覆盖 writeTo(BufferedSink sink) 而不是文件:

@Override
    public void writeTo(BufferedSink sink) throws IOException {
        StringReader in = new StringReader(yourHugeString);
        char[] buffer = new char[2048]; // you can modifiy the buffer
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                sink.write(new String(buffer).getBytes(), 0, read);
                mListener.onProgressUpdate(read);
            }
        } finally {
            in.close();
            mListener.onFinish(uploaded);
        }
}

yourHugeString 是您的字符串变量,其中包含非常大的字符串内容。我将 write() 转换为字符串,因为 read() 需要 char[]write() --> byte[]

然后修改你的界面:

void postSpecialData(SpecialRequestBody base64, Callback callback);