title: Java Proxy Output Stream corrupted with null bytes
body: <p>We have a JSP which is supposed to fetch a PDF from an internal URL and pass this PDF on to the client (like a proxy).</p>
  
  <p>The resulting download is corrupted. After about 18'400 bytes we only get 00 bytes till the end. Interestingly the download is exactly the right size in bytes.</p>
  
  <p><a href="https://i.stack.imgur.com/4MAOo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4MAOo.png" alt="binary difference"></a></p>
  
  <pre><code>    // Get the download
      URL url = new URL(url);
      HttpURLConnection req = (HttpURLConnection)url.openConnection();
      req.setDoOutput(true);
      req.setRequestMethod("GET");
  
      // Get Binary Response
      int contentLength = req.getContentLength();
      byte ba[] = new byte[contentLength];
      req.getInputStream().read(ba);
      ByteArrayInputStream in = new ByteArrayInputStream(ba);
  
      // Prepare Reponse Headers
      response.setContentType(req.getContentType());
      response.setContentLength(req.getContentLength());
      response.setHeader("Content-Disposition", "attachment; filename=download.pdf");
  
      // Stream to Response
      OutputStream output = response.getOutputStream();
      //OutputStream output = new FileOutputStream("c:\\temp\\op.pdf");
      int count;
      byte[] buffer = new byte[8192];
      while ((count = in.read(buffer)) &gt; 0) output.write(buffer, 0, count);
  
      in.close();
      output.close();
  
      req.disconnect();
  </code></pre>
  
  <p>UPDATE 1: I'm not the only one seeing Java stop streaming at 4379 bytes (<a href="https://community.oracle.com/thread/1206095?start=0&amp;tstart=0" rel="nofollow noreferrer">link</a>).</p>
  
  <p>UPDATE 2: If I do output.flush after every write I get more data 14599 bytes and then the nulls. Must have something to do with tomcat's output buffer limit.</p>