Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java okHttp reuse keep-alive connection

How to reuse http keep-alive connection via okHttp?

My code sample:

public class MainWithOkHttp {

    static OkHttpClient _client = new OkHttpClient();

    public static void main(String[] args) {
        ...
        query1();
        ...
        // in this request
        Request _request = new Request.Builder()
            .url("...")
            .addHeader("connection", "keep-alive")
            .addHeader("cookie", _cookie)
            .post(postParams)
            .build();
        // in this request my previous session is closed, why?
        // my previous session = session created in query1 method
        Response _response = _client.newCall(_request).execute();
        ...
    }

    ...
    private static void query1() {
        ...
        Request request = new Request.Builder()
            .url("...")
            .addHeader("connection", "keep-alive")
            .addHeader("cookie", _cookie)
            .get()
            .build();
        Response _response = _client.newCall(request).execute();
        ...
    }
    ...

}

So, I'm calling query1() method. In this method connection opened, session in server side created and cookie with sessionId received.

But, when I'm performing another query to server - my previous connection is not used and session on server already closed. Session life time in server is not small, so the problem not in life time.

PS: I'm getting captcha from server and recognizing the captcha code, then performing query with captcha code to server. But captcha in server side not recognized, because session already closed and captcha code stored in session.

like image 702
Vüsal Avatar asked Oct 22 '15 13:10

Vüsal


1 Answers

Eventually, the following code is working for me:

public class Main {

  static OkHttpClient _client = new OkHttpClient();

  public static void main(String[] args) throws IOException {
      performQuery();
  }

  private static void performQuery() throws IOException {
      Request firstRequest = new Request.Builder()
            .url("http://localhost/test/index.php")
            .get()
            .build();
      Response firstResponse = _client.newCall(firstRequest).execute();

      Request.Builder requestBuilder = new Request.Builder()
            .url("http://localhost/test/index.php");

      Headers headers = firstResponse.headers();

      requestBuilder = requestBuilder.addHeader("Cookie", headers.get("Set-Cookie"));

      Request secondRequest = requestBuilder.get().build();
      Response secondResponse = _client.newCall(secondRequest).execute();
  }
}

It seems, the problem was with _cookie object.

like image 108
Vüsal Avatar answered Sep 18 '22 16:09

Vüsal