【问题标题】:How to measure upload progress of a huge String with Retrofit 2?如何使用 Retrofit 2 测量巨大字符串的上传进度?
【发布时间】:2019-05-14 10:19:43
【问题描述】:

我使用 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 变量既不是文件也不是存储在某处。 例如,如何获取上传进度以使其在进度条上可见?

【问题讨论】:

    标签: android rest http-post retrofit2 okhttp3


    【解决方案1】:

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

    @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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-11
      • 2017-02-20
      • 2021-07-06
      • 2017-04-13
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多