2

How can I read the String / byte array that is the payload POSTed to a GAE java app?

Is there a simple way to get those bytes without using Jackson / jersey or similar libraries?

Angular side uses something like:

 $http({
        method : 'POST',
        url : 'http://APPID.appspot.com/api/get-reference-locales-for',
        data : {
            'param' : value,
            'param2' : value2
        })

Java side has

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException { ...

I expected that there would be a simple way to get the string {'param':1,'param':2} from the req object but I can seem to find it.

epeleg
  • 10,347
  • 17
  • 101
  • 151
  • It's not posted as JSON is it? It's posted as a HTML form - you know, as query parameters. – tom Dec 16 '14 at 15:14
  • I think that it IS sent as JSON in the request body/ payload. any idea how to read it from there ? – epeleg Dec 17 '14 at 08:28
  • You should look into using a higher level abstraction, an MVC or similar like spring, struts, thundr etc. If you wish to do this yourself directly you need to consume the req.getInputStream() into a byte array, then convert it into a string using the correct character encoding, which will be in a request header. – Nick Dec 17 '14 at 08:41
  • If it is JSON then I don't know why you'd not use Jackson to parse the request body. That's what it's for. If you don't want the dependency then use javax.json instead. – tom Dec 17 '14 at 09:58
  • Just to explain that I want to be able to control the output even if the JSON that was sent was malformed - or to be able to even test if what was sent was JSON at all. so the libraries that automatically respond with an error if the data is not exactly JSON are not suitable for me. – epeleg Dec 17 '14 at 10:24

1 Answers1

2

Based on the answer here: Getting request payload from POST request in Java servlet

I am now using:

public String getRequestPayload(HttpServletRequest req) {
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader;
    String data = "";
    try {
        reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        data = buffer.toString();   
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return data;
}
Community
  • 1
  • 1
epeleg
  • 10,347
  • 17
  • 101
  • 151