0

What is the general approach to retrieve binary data that is posted to a Java Servlet? A byte[] is being posted to this servlet and I think I have to somehow parse the HttpServletRequest.getInputStream() and pull out the byte[] contents. Any ideas on how to change the below code to accomplish this?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
          InputStream inputStream = request.getInputStream();
          if (inputStream != null) {
           bufferedReader = new BufferedReader(new InputStreamReader(
        inputStream));
           char[] charBuffer = new char[128];
           int bytesRead = -1;
           while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
           }
          } else {
           stringBuilder.append("");
          }
        } catch (IOException ex) {
          throw ex;
        } finally {
          if (bufferedReader != null) {
           try {
            bufferedReader.close();
           } catch (IOException ex) {
            throw ex;
           }
          }
        }
        String body = stringBuilder.toString();
        System.out.println(body);
}

2 Answers 2

1

Don't wrap your inputstream in any "Reader"s, as they convert from bytes to characters, and you want the bytes.

1

yes. ditch all the Readers and use the InputStream you were handed on the 3rd line. if you don't understand the relationship between byte[] and InputStream, i would suggest reading the API docs and some good java tutorials.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.