Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 274
RKS Avatar asked Nov 19 '16 10:11

RKS


3 Answers

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);
like image 116
DRY Believer Avatar answered Nov 04 '22 19:11

DRY Believer


Decreasing log level from BODY to HEADERS, BASIC or NONE solved this problem for me

like image 7
MakBeard Avatar answered Nov 04 '22 20:11

MakBeard


I figured out yet another case for twice called writeTo() method. I use OkHttpClient without Retrofit and HttpLoggingInterceptor, and I have the twice called problem.

Solution: the problem appears after upgrade Android Studio to 3.1.1 and enable Advanced Profiling in run project configuration. So disable Advanced Profiling.

like image 6
ilyamuromets Avatar answered Nov 04 '22 21:11

ilyamuromets