title: Java okHttp reuse keep-alive connection
body: <p>How to reuse http keep-alive connection via okHttp?</p>
  
  <p>My code sample:</p>
  
  <pre><code>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();
          ...
      }
      ...
  
  }
  </code></pre>
  
  <p>So, I'm calling <code>query1()</code> method. In this method connection opened, session in server side created and cookie with sessionId received. </p>
  
  <p>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.</p>
  
  <p>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.</p>