Java okhttp reuses keep alive connections

How to reuse HTTP keep alive connections through okhttp?

My code example:

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",_cookie)
            .get()
            .build();
        Response _response = _client.newCall(request).execute();
        ...
    }
    ...

}

So, I'm calling the query1 () method In this method, the connection is opened, a session is created on the server side, and a cookie with sessionid is received

However, when I execute another query to the server - my previous connection is not used and the session on the server has been closed The session lifetime in the server is not small, so the problem is not lifetime

PS: I get the verification code from the server and identify the verification code, and then use the verification code to query the server However, the verification code on the server side cannot be recognized because the session has been closed and the verification code is stored in the session

Solution

Finally, the following code works 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 that the problem is_ On the cookie object

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>