How to convert an HttpServletRequest to String?

這個,滿多人去實作的,我最後是用這一個解法:

// Convert the request inputStream to string
String str_request = IOUtils.toString(request.getInputStream());
// Count the actual content length of the http request
char[] char_array_request = str_request.toCharArray();
int count = char_array_request.length;
// Create a inputStream for further manipulation
requestStream = new ByteArrayInputStream(str_request.getBytes());

檔案下載:
http://commons.apache.org/downloads/download_io.cgi

To solve the problem, i import the Apache Commons IO to the project and modify the code. This time, i convert the inputStream to string for counting. Then i create a new InputStream from the string for manipulation.


 

其他解法1:

String httpServletRequestToString(HttpServletRequest request) throws Exception {

    ServletInputStream mServletInputStream = request.getInputStream();
    byte[] httpInData = new byte[request.getContentLength()];
    int retVal = -1;
    StringBuilder stringBuilder = new StringBuilder();

    while ((retVal = mServletInputStream.read(httpInData)) != -1) {
        for (int i = 0; i < retVal; i++) {
            stringBuilder.append(Character.toString((char) httpInData[i]));
        }
    }

    return stringBuilder.toString();
}

 

其他解法2:

It seems like your while loop doesn’t do anything here, because in your case, bytesRead is always -1 thus it will never get into the loop at all, and further, you don’t use your bufferedReader at all to read from the input stream:-

    int bytesRead = -1;
    while (bytesRead != -1) {
        stringBuilder.append(charBuffer, 0, bytesRead);
    }

Try this:-

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(req.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }

    String body = stringBuilder.toString();

    System.out.println(body);
    out.println(body);

}

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *