title: Java byte array sent with contentType: application/octetstream losing negative byte values
body: <p>I have an array of integers in java, and I am converting it to a ByteArray</p>
  
  <pre class="lang-java prettyprint-override"><code>public byte[] intArrayToByteArray(int[] arr) {
  
      // create byte buffer
      ByteBuffer byteBuf = ByteBuffer.allocate(arr.length*4);
  
      // create a view of the byte buffer as a int buffer
      IntBuffer intBuf = byteBuf.asIntBuffer();
      intBuf.put(arr);
  
      return byteBuf.array();
  }
  </code></pre>
  
  <p>turns an array like this <code>[27759020,27682392]</code>
  into a byte array like this:  </p>
  
  <p><code>[1,-89,-111,-84,1,-90,102,88]</code></p>
  
  <p>This seems all good to me, the problem is when I send data over in a multipart formdata response (using Content-Type: application/octet-stream).</p>
  
  <p>I'm using <code>MultipartEntityBuilder</code> to build the response in my servlet like this</p>
  
  <pre><code>MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
  mpBuilder.setBoundary("--boundary");
  
  mpBuilder.addTextBody("meta", json,  ContentType.APPLICATION_JSON);
  mpBuilder.addBinaryBody("HeightMap", bytes);
  
  HttpEntity multipartData = mpBuilder.build();
  
  try(OutputStream out = response.getOutputStream()) {
      multipartData.writeTo(out);
      response.setStatus(HttpServletResponse.SC_OK);
  } catch(Exception e) {
      log.error(" --- Failed writing multipart form data to response. ---");
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  }
  </code></pre>
  
  <p>I get a string of string encoded values like this.</p>
  
  <pre><code>Content-Disposition: form-data; name="HeightMap"
  Content-Type: application/octet-stream
  Content-Transfer-Encoding: binary
  
  ����fX 
  </code></pre>
  
  <p>which decodes in javascript to <code>[1, 65533, 65533, 65533, 1,65533, 102, 88]</code></p>
  
  <p>the function used to decode the string is here</p>
  
  <pre class="lang-js prettyprint-override"><code>private static toUint8Array(dataString: string) {
      let byteArr = new Uint8Array(dataString.length);
      for(let i=0; i &lt; dataString.length; i++) {
          let byte = dataString.charCodeAt(i) &amp; 0xFF;
          byteArr[i] = byte;
      }
      return byteArr;
  }
  </code></pre>
  
  <p>(the value gets clamped in this function to 253 from 65533 but originally that's what <code>.charCodeAt(i)</code> gives)</p>
  
  <p>you can see that each of the negative byte values from Java have been replaced by the UTF-8 'unknown character' value: 65533.</p>
  
  <p>Is it possible to use another type of character encoding that will preserve the values of my bytes? Can I turn off the unknown value replacement that UTF-8 encoding does?</p>
  
  <p>Help is appreciated.</p>