0

Due to too many connection is open, after some days server is hanging because of open file issues.

I have constructor which create a new object every time

OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslContext.getSocketFactory())
                                .build();

After that I have written a separate method for GET and POST method.:

Response response = null;

Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
requestBuilder.header("appId", BuildConfig.APPLICATION_ID);
requestBuilder.header("appVersion", BuildConfig.VERSION_NAME);
requestBuilder.header("deviceId", UserPrefs.getDeviceID());
requestBuilder.header("accessToken", UserPrefs.getAccessToken());
requestBuilder.header("versionCode", String.valueOf(BuildConfig.VERSION_CODE));
requestBuilder.header("securityCounter", UserPrefs.getSecurityToken());

Request okHttpRequest = requestBuilder.build();

OkHttpClient.Builder b = new OkHttpClient.Builder();
                b.readTimeout(65, TimeUnit.SECONDS);
                b.writeTimeout(65, TimeUnit.SECONDS);
                b.connectTimeout(65, TimeUnit.SECONDS);
                client = b.build();

                response = client.newCall(okHttpRequest).execute();

After that based on the "response.code()" response is handled in the Fragment or Activity. Finally,

I'm calling the response.close().

Now in Fragment I've created an Async Class and Calling this GET and POST method in the doInBackground method and response is handled in the onPostExecute method of the same class.

Like this

 OkHttpClientAPI okHttpClientAPI = new OkHttpClientAPI(LoginActivity.this);
 response = okHttpClientAPI.doPostRequest(url, formBody, LoginActivity.this);

Instead of creating a new connection always can we re-use the connection pool.

So it won't exceed the 65535 count on the server side.

Kalariya_M
  • 1,357
  • 12
  • 20
Likith Ts
  • 296
  • 1
  • 7
  • 18

1 Answers1

0

Do like this in your constructor

    OkHttpClient okHttpClient; // global variable 
     public YourConstructor() {
            if (okHttpClient == null) {
                okHttpClient = new OkHttpClient();
            }
        }
Rajasekhar
  • 2,345
  • 1
  • 13
  • 20
  • yes it will take only one connection always. if you need full code ask i can help – Rajasekhar Oct 25 '17 at 07:27
  • I just tried the change. Still I can see in server new connection is established for each request. So I need to understand more on it. – Likith Ts Oct 25 '17 at 07:44