Search code examples
javaandroiduploadretrofit2

Retrofit 2 RequestBody writeTo() method called twice


Retrofit 2 RequestBody writeTo() method called twice, the code which I used is given below:

ProgressRequestBody requestVideoFile = new ProgressRequestBody(videoFile, new ProgressRequestBody.UploadCallbacks() {

    VideoUploadStore store = new VideoUploadStore();

    @Override
    public void onProgressUpdate(int percentage) {
        if (!mIsCancelled) {
            Log.i("UploadServiceManager", "Read Percentage : " + percentage);
            data.setUploadPercentage(percentage);
            store.updateUploadData(data);
        }
    }

    @Override
    public void onError() {
        if(!mIsCancelled) {
            data.setUploadPercentage(0);
            store.updateUploadData(data);
        }
    }

    @Override
    public void onFinish() {

    }
});
MultipartBody.Part multipartVideo = MultipartBody.Part.createFormData("File", videoFile.getName(), requestVideoFile);

Solution

  • The solution below might help you out , although it might be too late. :p

    Remove HttpLoggingInterceptor Object in your Api Client which will not execute writeTo() function twice.Basically , HttpLoggingInterceptor loads the data buffer first ( for internal logging purpose ) by calling writeTo() and then again calls writeTo() for uploading the data to server.

      HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
      logging.setLevel(HttpLoggingInterceptor.Level.BODY);
      httpClient.addInterceptor(logging);