title: HTTP 1.1 Persistent Connections using Sockets in Java
body: <p>Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket.  However, upon making a second request, I get no response from the server (or there's a problem with the stream - it doesn't provide any more input). If I make the requests in order (Request, request, read) it works fine, but (request, read, request, read) doesn't.</p>
  
  <p>Could someone shed some insight onto why this might be happening? (Code snippets follow). No matter what I do, the second read loop's isr_reader.read() only ever returns -1.</p>
  
  <pre><code>try{
          connection = new Socket("SomeServer", port);
          con_out = connection.getOutputStream();
          con_in  = connection.getInputStream();
          PrintWriter out_writer = new PrintWriter(con_out, false);
          out_writer.print("GET http://somesite HTTP/1.1\r\n");
          out_writer.print("Host: thehost\r\n");
          //out_writer.print("Content-Length: 0\r\n");
          out_writer.print("\r\n");
          out_writer.flush();
  
          // If we were not interpreting this data as a character stream, we might need to adjust byte ordering here.
          InputStreamReader isr_reader = new InputStreamReader(con_in);
          char[] streamBuf = new char[8192];
          int amountRead;
          StringBuilder receivedData = new StringBuilder();
          while((amountRead = isr_reader.read(streamBuf)) &gt; 0){
              receivedData.append(streamBuf, 0, amountRead);
          }
  
  // Response is processed here.
  
          if(connection != null &amp;&amp; !connection.isClosed()){
              //System.out.println("Connection Still Open...");
  
          out_writer.print("GET http://someSite2\r\n");
          out_writer.print("Host: somehost\r\n");
          out_writer.print("Connection: close\r\n");
          out_writer.print("\r\n");
          out_writer.flush();
  
          streamBuf = new char[8192];
          amountRead = 0;
          receivedData.setLength(0);
          while((amountRead = isr_reader.read(streamBuf)) &gt; 0 || amountRead &lt; 1){
              if (amountRead &gt; 0)
                  receivedData.append(streamBuf, 0, amountRead);
          }
  }
          // Process response here
      }
  </code></pre>
  
  <p>Responses to questions:
  Yes, I'm receiving chunked responses from the server.
  I'm using raw sockets because of an outside restriction.</p>
  
  <p>Apologies for the mess of code - I was rewriting it from memory and seem to have introduced a few bugs.</p>
  
  <p>So the consensus is I have to either do (request, request, read) and let the server close the stream once I hit the end, or, if I do (request, read, request, read) stop before I hit the end of the stream so that the stream <em>isn't</em> closed.</p>