How to handle retrofit socket timeout for uploading files in android kotlin?

Deadly 提交于 2020-07-23 08:37:18

问题


 var client = OkHttpClient()
            val builder = OkHttpClient.Builder()
            val gson = GsonBuilder()
                .setLenient()
                .create()

                builder.addInterceptor(AddCookiesInterceptor(mcontext))
                builder.addInterceptor(ReceivedCookiesInterceptor(mcontext))
                builder.callTimeout(100,TimeUnit.SECONDS)

            client = builder.build()
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
 //                   .addConverterFactory(ScalarsConverterFactory.create())
                .build()

This is my retrofit client service builder. For normal api functions with json response callback it works fine. Is there any modification required for an large file upload?

With current scenario, uploading 20 mb data, takes more time in slow network connection which returns a socket timeout exception.

Uploading as multipart body

 var fileBody : ProgressRequestBody? = null
   fileBody = ProgressRequestBody(file,"*/*",this@CaseFileUploadFragment)
        var fileToUpload: MultipartBody.Part = 
   MultipartBody.Part.createFormData("image",file.name, fileBody)
        var filename : RequestBody = 
    RequestBody.create(MediaType.parse("text/plain"),file.getName())

and following is the function used

 @Multipart
    @POST("{urlMpString}")
    fun uploadFile(
        @Path ("urlMpString") urlEndString : String, @Part file: MultipartBody.Part, @Part("file") requestBody: RequestBody,
        @Part("apiInfo") `object1`: JsonObject,  @Part("parameters") `object2`: JsonObject
    ): Call<JsonObject>

Everything works fine for small data files. Any suggestions and help will be appreciated. Thanks


回答1:


Try below code for okHttpClient

OkHttpClient okHttpClient = new OkHttpClient.Builder()  
    .connectTimeout(5, TimeUnit.MINUTES)
    .readTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(15, TimeUnit.SECONDS)
    .build();


来源:https://stackoverflow.com/questions/61896772/how-to-handle-retrofit-socket-timeout-for-uploading-files-in-android-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!