简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM