Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get the content out of a HttpServletRequest

I'm trying to get the contents of a HttpServletRequest. Here is how I'm doing it:

// Extract the request content
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
String content = "";

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

content =  stringBuilder.toString();
System.out.println("Length: " + request.getContentLength());

The String "content" is empty. However, the last line displays

Length: 53

which is exactly the length of the content I'm expecting. If it helps, here is how I trigger this servlet:

wget --post-data='{"imei":"351553012623446","hni":"310150","wdp":false}' http://localhost:8080/test/forward
like image 537
Saulo Silva Avatar asked Nov 23 '25 22:11

Saulo Silva


1 Answers

Well, I finally found the answer! Turns out that the value of "post-data" that is given to wget becomes the name of a parameter in the request. In other words, if I get the parameter name of the first (and only) parameter in the request, I will get that value. The code to extract it is trivial:

// Extract the post content from the request
@SuppressWarnings("unchecked")
Enumeration<String> paramEnum = request.getParameterNames();
paramEnum.hasMoreElements();
String postContent = (String) paramEnum.nextElement();

Thanks everyone for your responses!

like image 143
Saulo Silva Avatar answered Nov 26 '25 12:11

Saulo Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!