Java okHttp重用keep-alive连接

时间:2015-10-22 13:08:17

标签: java session keep-alive okhttp session-reuse

如何通过okHttp重用http keep-alive连接?

我的代码示例:

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();
        ...
    }
    ...

}

所以,我正在调用query1()方法。在此方法中,打开了连接,在服务器端创建了会话,并且收到了带有sessionId的cookie。

但是,当我向服务器执行另一个查询时 - 我之前的连接未被使用,服务器上的会话已经关闭。服务器中的会话生存时间不小,所以问题不在于终身。

PS:我从服务器获取验证码并识别验证码,然后使用验证码对服务器执行查询。但是服务器端的验证码无法识别,因为会话已经关闭,验证码存储在会话中。

1 个答案:

答案 0 :(得分:0)

最终,以下代码对我有用:

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();
  }
}

似乎问题出在_cookie对象上。