Retrofit2.0 set connection timeout

Keywords: Android network Retrofit

Retrofit2.0, a network request framework, has been in use for a long time. Recently, there was an episode.

There is an interface that returns a large amount of data due to business reasons. When the network is not good, the request fails

That is to say, the onfailure() method is called back. After testing, the method will be called back in about 10 seconds.

Go to the background to verify that the data request is successful and successful, that is, it is not a data problem. The problem is that if the request is not processed successfully within 10 seconds due to the large amount of data requested, the request will fail.

The solution is to set a connection timeout for the request frame

   // Retrofit Network data request
    public static RetrofitAPI Retrofit() {
        if (retrofitAPI == null) {
            retrofitAPI = new Retrofit.Builder()
                    .baseUrl(ApkManager.baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(genericClient())
                    .build()
                    .create(RetrofitAPI.class);
        }
        return retrofitAPI;
    }


    public static String date = "000000"; //Record version release time

    public static OkHttpClient genericClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("User-Agent", "Magikare/Therapist/"+date)
                                .build();
                        return chain.proceed(request);
                    }
                }).connectTimeout(30, TimeUnit.SECONDS).      // Set connection timeout
                readTimeout(30, TimeUnit.SECONDS).
                writeTimeout(30, TimeUnit.SECONDS).build(); 

        return httpClient;
    }

Posted by exally on Sun, 08 Dec 2019 18:47:34 -0800