title: How can I read a binary file from a socket input stream which includes textual headers?:
body: <p>OK, so I have a socket <code>InputStream</code> over which the server is sending a data stream containing a number of lines of header text followed by a binary stream of bytes making up the pdf file it is sending (of a length specified in the header section). The server, which I can't control, does not close the data stream after it sends its data so i must read the exact amount of bytes from the stream and then close it myself from the client end.</p>
  
  <p>So, my question is, how do you or are there any utilities which will allow me to easily read the headers (as text) and then read an exact amount of bytes from the same input sream?</p>
  
  <p>I've tried various <code>Reader</code> classes which work great for the headers, but as I've learned not so great for the binary content of the data (<code>Reader</code>s work with characters not bytes).  Utilities such as apache commons <code>IOUtils</code> don't work for me because the stream remains open/unterminated and attempts at <code>IOUtils.toBytes(inputStream)</code> hang indefinitely.</p>
  
  <p>The solution seems to be to work with <code>Stream</code> classes rather than <code>Reader</code> classes, but it seems so low level that there must be utilities out there to help me with this.  Reading the binary data using a <code>DataInputStream</code> seems easy enough, but I'm stumped as to how to read the headers.  Any advice?</p>
  
  <p>EDIT:  Here is a sample message:</p>
  
  <pre><code>http/1.0 200 OK
  content-type: application/doc_request
  content-length: 18813
  session-id: slukdcy71292645678312
  remote-addr: slukdcy7
  
  &lt;pdf binary data...&gt;
  </code></pre>
  
  <p>The new line between the headers and binary data determine the end of the headers and the start of the binary data.</p>