0

I use Retrofit 2 and a POST Rest call to send some data to backend. My rest interface looks like:

void postSpecialData(String base64, Callback callback);

whereas my Callback is Retrofit interface with:

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

I call then finally:

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");
            }
});

The encryptedBase64 variable is neither a File nor stored somewhere. How can I get the upload progress to make it visible on a progress bar for example?

Tranquillo
  • 235
  • 2
  • 13

1 Answers1

1

As in this example: Extend OkHttp3's RequestBody and overwrite writeTo(BufferedSink sink) for String yourHugeString instead of a file:

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

whereas yourHugeString is your string variable with very huge string content. I converted for write() to String, because, the read() requires char[] whereas write() --> byte[]

Then just modify your interface:

void postSpecialData(SpecialRequestBody base64, Callback callback);
Murat Ceven
  • 264
  • 1
  • 6