2012-02-14 89 views
0

檢索發佈到Java Servlet的二進制數據的一般方法是什麼?一個byte []被髮送到這個servlet,我想我必須以某種方式解析HttpServletRequest.getInputStream()並提取byte []內容。有關如何更改下面的代碼來完成此任何想法?解析HttpServletRequest中的二進制數據

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); 
} 

回答

1

不要將輸入流包裝在任何「讀取器」中,因爲它們會將字節轉換爲字符,並且您需要字節。

1

是的。把所有的讀者溝通起來,並使用你在第三行遞交的InputStream。如果你不明白byte []和InputStream之間的關係,我會建議閱讀API文檔和一些好的java教程。