Expand my Community achievements bar.

SOLVED

Sling Post servlet getting java.lang.IllegalStateException: Request Data has already been read

Avatar

Level 7

In the post servlet binded with the resource type gives error 

java.lang.IllegalStateException: Request Data has already been read

while saving the dialog of component to which it is binded to.

 

InputStream stream = request.getInputStream();
This is the first line of doPost inside try block. How to resole this?

 

 @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
            throws ServletException, IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            resourceResolver = request.getResourceResolver();
            InputStream stream = request.getInputStream();
            InputStreamReader reader = new InputStreamReader(stream);
            JsonElement json = JsonParser.parseReader(reader);
            .....logic.....
        } catch (Exception e) {
            log.error("Errors in Post Call {}", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

If I am not wrong you are trying to get the request body to POJO class. In that case, you can use Gson,

Gson gson = new Gson();
MyPojo mypojo = gson.fromJson(request.getReader(), MyPojo.class);

 

View solution in original post

2 Replies

Avatar

Community Advisor

@Ronnie09 may I know what are you trying to achieve? I believe aem already does one sling post to save authored data to jcr repository on save of component dialog, that's the reason why you are not able to read that posted data one more time.

Avatar

Correct answer by
Community Advisor

If I am not wrong you are trying to get the request body to POJO class. In that case, you can use Gson,

Gson gson = new Gson();
MyPojo mypojo = gson.fromJson(request.getReader(), MyPojo.class);