从HttpServletRequest解析二进制数据

时间:2012-02-14 01:47:34

标签: java servlets

检索发布到Java Servlet的二进制数据的一般方法是什么?一个byte []被发布到这个servlet,我想我必须以某种方式解析HttpServletRequest.getInputStream()并拉出byte []内容。有关如何更改以下代码以实现此目的的任何想法?

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 个答案:

答案 0 :(得分:1)

不要将输入流包装在任何“读取器”中,因为它们会从字节转换为字符,并且您需要字节。

答案 1 :(得分:1)

是肯定的。抛弃所有读者并使用你在第3行传递的InputStream。如果你不理解byte []和InputStream之间的关系,我建议你阅读API文档和一些很好的java教程。