Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate request at same time in Retrofit 2

I am facing an issue of duplicate requests for single API, I am using retrofit 2.When i try to call one API, 3 times its hitting the server. same API is called multiple times with in fraction of sections. Here is the code:

 public Retrofit retrofit() {
    String UrlBasePath="";

    if (mRetrofit == null) {
        if (builder == null) {
            builder = new OkHttpClient.Builder();
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                HttpUrl httpUrl = original.url().newBuilder()
                        .build();
                String credentials = BuildConfig.ApiUserName + ":" + BuildConfig.ApiPassword;

                if (BuildConfig.ApiUserName.equals("APIUSERNAME") || BuildConfig.ApiPassword.equals("APIPASSWORD")) {
                    AnalyticsManager.sendEvent("RETROERROR", "AUTHENTICATIONFAILED", "FAILED");
                }

                final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
                // Request customization: add request headers
                Request request = original.newBuilder()
                        .addHeader("Authorization", basic)
                        .addHeader("User-Agent", "android")
                        .method(original.method(), original.body())
                        .url(httpUrl)
                        .build();
                return chain.proceed(request);

            }
        }).connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS);

        if(BuildConfig.BUILD_TYPE.equalsIgnoreCase("debug")) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logging);
        }

        UrlBasePath = UrlParser.httpsUrlBasePath;

        OkHttpClient client = enableTls12OnPreLollipop(builder).build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(UrlBasePath)
                .addConverterFactory(new ToStringConverterFactory())
                .addConverterFactory(GsonConverterFactory.create(gsonMapper()))
                .client(client)
                .build();
    }
    }
    return mRetrofit;
}

Called this method in Activity: Activity code

private final BmApiInterface RetroApiCall = RetroConnect.getInstance().retrofit().create(BmApiInterface.class); //global variable

Call<SingleLoginParser> loginCall = RetroApiCall.getLoginAPI(MatriidDet+"~"+Constants.APPVERSIONCODE,System.currentTimeMillis(),
                        Constants.constructApiUrlMap(new UrlParser().UrlGenerator(Constants.COMMON_LOGIN, new String[]{}))
                );
                mCallList.add(loginCall);
                RetroConnect.getInstance().AddToEnqueue(loginCall, mListener, RequestType.COMMON_LOGIN);

Can some one help me!!

like image 746
sree Avatar asked Mar 16 '18 10:03

sree


People also ask

What is the difference between retrofit and retrofit2?

In Retrofit 1.9, if the fetched response couldn't be parsed into the defined Object, failure will be called. But in Retrofit 2.0, whether the response is be able to parse or not, onResponse will be always called. But in the case the result couldn't be parsed into the Object, response. body() will return as null.

Is retrofit RESTful?

Overview. Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square.


1 Answers

It possible when server response is slow and timeout then retfofit2 retry same request multiple times. To prevent this you have to use .retryOnConnectionFailure(false)method with OkHttpClient.

Sample code :

OkHttpClient okHttpClient= null;
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory(),trustManager)
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES)
                //.sslSocketFactory(sslSocketFactory, trustManager)
                .followRedirects(false)
                .followSslRedirects(false)
                .retryOnConnectionFailure(false)
                .cache(null)//new Cache(sContext.getCacheDir(),10*1024*1024)
                .build();

In previous version have some bugged and fixed after retrofit:2.1.0

So you should use updated version of retrofit2 and okhttp3:

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1' 

Issue discussion:

https://github.com/square/okhttp/pull/1259#issuecomment-68430264

like image 183
Majedur Avatar answered Oct 03 '22 03:10

Majedur