Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Retrofit2/okhttp3 upload file,the upload action always performs twice,one fast ,and other slow

I use a ProgressRequestBody to show a progress for the upload action.

@Override
public void writeTo(BufferedSink sink) throws IOException {
    // see https://github.com/square/okhttp/issues/1587
    // JakeWharton commented on 28 Apr 2015  's answer
    final BufferedSink progressSink = Okio.buffer(new ForwardingSink(sink) {
        long bytesWritten = 0L;
        long contentLength = 0L;

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            if (contentLength == 0) {
                contentLength = contentLength();
            }
            bytesWritten += byteCount;
            mListener.onProgressUpdate(bytesWritten,contentLength,bytesWritten == contentLength);
            System.out.println("--byte--"+bytesWritten);
            super.write(source, byteCount);
        }
    });
    requestBody.writeTo(progressSink);
    System.out.println("--byte-- start---");
    progressSink.flush();
    System.out.println("--byte-- end---");
}

this method was called twice every time I performed the action of upload. at first, I considered the problem may be the Interceptor which was added into okhttpclient for log,but it was not. who could help me? thanks

more code :

public interface UploadInterface {

@Multipart
@POST("path")
Call<JsonBase<Result>> uploadFile(
        @Query("_appTicket") String cookie, 
        @Query("Id") String id, 
        @Part MultipartBody.Part requestBody
);
}

upload action:

final ProgressRequestBody progressRequestBody
                            = new ProgressRequestBody(
                            RequestBody.create(
                                    MediaType.parse("multipart/form-data"),
                                    tempZip
                            )
                    );
MultipartBody.Part part = MultipartBody.Part
                            .createFormData("file","upload",progressRequestBody);
                    final Call<JsonBase<JsonUploadResult>> call 
                            = uplocaInterface.uploadFile(cookie,s,part);
like image 580
belle tian Avatar asked Dec 18 '22 15:12

belle tian


1 Answers

Seems you are using HttpLoggingInterceptor which called writeTo for the Request body. You could ignore the issue as HttpLoggingInterceptor should be disabled for release builds or overwrite intercept method of HttpLoggingInterceptor and disable it for this particular upload request.

like image 200
Andrey T Avatar answered Dec 27 '22 13:12

Andrey T