Required request body is missing public java lang string

How to avoid HttpMessageNotReadableException when using ContentCachingRequestWrapper with Java Servlet Filters

If you’re using a ContentCachingRequestWrapper from Spring, you may be confused to find errors, similar to the below, from your application:

HTTP/1.1 400 Content-Type: application/json Transfer-Encoding: chunked Date: Mon, 25 May 2020 15:45:29 GMT Connection: close < "timestamp": "2020-05-25T15:45:33.739+0000", "status": 400, "error": "Bad Request", "message": "Required request body is missing: public org.springframework.http.ResponseEntityme.jvt.hacking.controller.Controller.echo(java.lang.String)", "path": "/" > 

This appears to be because the ContentCachingRequestWrapper doesn’t cache the raw ServletInputStream , which is then consumed further down the line by Spring when trying to use @RequestBody .

The solution is detailed in my article Reading a Servlet/Spring Request Body Multiple Times, and involves not using the ContentCachingRequestWrapper , but instead using a custom class that can cache the ServletInputStream .

How to avoid receiving `Required request body is missing` errors when using a `ContentCachingRequestWrapper`.

Jamie Tanna

Written by Jamie Tanna on Mon, 25 May 2020 19:56:08 BST , and last updated on Wed, 02 Mar 2022 13:34:19 UTC .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

Читайте также:  Тег label для html

Has this content helped you? Did it solve that difficult-to-resolve issue you’ve been chasing for weeks? Or has it taught you something new you’ll be able to re-use daily?

Please consider supporting me so I can continue to create content like this!

This post was filed under articles.

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.

Want to get in touch? Drop me an email at hi@jamietanna.co.uk. I try to get back to everything, if I don’t reply in a couple of weeks, feel free to give me a nudge!

You can also check out a list of all the places /elsewhere you can find me.

© 2023 Jamie Tanna. Post content and code snippets licensing is detailed on respective pages, otherwise default to Creative Commons Attribution Non Commercial Share Alike 4.0 International and Apache License 2.0.
Site design released under the MIT License, based on Hack.css.
Proudly hosted on AWS using S3 + CloudFront, deployed by GitLab CI, and generated by 4693e31b7f on Wed, 02 Mar 2022 13:34:19 +0000..

Источник

Spring framework HttpMessageNotReadableException: Required request body is missing

In order to accept an empty body you can use the required param in the RequestBody annotation:, To receive RequestParam in POST you can refer to this question: stackoverflow.com/questions/17964841/… You can also pass the data through the body, which makes sense too, since it is a post request. – L. Figueredo Oct 24 ’18 at 17:07 ,You have to pass that as JSON in your body, if it’s a POST request.

To handle this values, you can do the following:

@PostMapping(path="/login") public ResponseEntity loginUser(@RequestParam("email") String email, @RequestParam("password") String password) < //your imp >

In order to accept an empty body you can use the required param in the RequestBody annotation:

@RequestBody(required = false) 

Answer by Valentina Nolan

Successfully merging a pull request may close this issue., Pull requests , Pull requests 0

Answer by Camilla Little

So I changed @Requestbodys to a single @RequestBody like andreim said, it fixed my bad request error but for some reason the account username would always be null when the post request went through.,If you add any files,it will delete all existing files related to this question-(questions only answer remains unchanged),NOTE: if you want to write less, you can use @PostMapping instead of @RequestMapping(method = RequestMethod.POST).

When I try to use curl to make the POST request I get an error that says

 com.example.AccountRestController.add(java.lang.String,java.lang.String)","path":"/users/add"> 

The curl command I’m using

curl -X POST --data '' -H "Content-Type:application/json" http://localhost:8080/users/add 

AccountRestController

@RequestMapping(method = RequestMethod.POST, value = "/add", produces = < MediaType.APPLICATION_JSON_VALUE>) ResponseEntity add(@RequestBody String username, @RequestBody String password) < Account result = accountRepository.save(new Account (username, password)); return new ResponseEntity<>(result, HttpStatus.CREATED); > 

Answer by Colby Carter

If you’re using a ContentCachingRequestWrapper from Spring, you may be confused to find errors, similar to the below, from your application:,This appears to be because the ContentCachingRequestWrapper doesn’t cache the raw ServletInputStream, which is then consumed further down the line by Spring when trying to use @RequestBody.,Reading a Servlet/Spring Request Body Multiple Times

If you’re using a ContentCachingRequestWrapper from Spring, you may be confused to find errors, similar to the below, from your application:

HTTP/1.1 400 Content-Type: application/json Transfer-Encoding: chunked Date: Mon, 25 May 2020 15:45:29 GMT Connection: close < "timestamp": "2020-05-25T15:45:33.739+0000", "status": 400, "error": "Bad Request", "message": "Required request body is missing: public org.springframework.http.ResponseEntityme.jvt.hacking.controller.Controller.echo(java.lang.String)", "path": "/" > 

Answer by Mylo Lara

2018-01-29 17:04:55.765 WARN 10768 — [nio-8088-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.demo.controller.HelloController.add(java.lang.String,java.util.List), Fire knowledge online question answering activity small program replay ,>Public String add (@RequestBody Bean bean) is OKYou can also use @RequestBody Map < String, Object >map….

 type:"post", url: 'add', contentType:"application/json; charset=utf-8", dataType:"json", data:JSON.stringify(< content:"nihaoahaha", param:[,] >), success:function(data) < console.log(data); >>) 
@RequestMapping(value = "add", consumes = "application/json; charset=utf-8") public String add(@RequestBody String content, @RequestBody List param) < System.out.println("param:" + param); Return "success"; >Error reporting information: 2018-01-29 17:04:55.765 WARN 10768 --- [nio-8088-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.demo.controller.HelloController.add(java.lang.String,java.util.List)

Answer by Jolie Xiong

2019-05-30 16:47:05.116 WARN [PIE,5cf04149bdeeeb771519484aef6e7abc,1519484aef6e7abc,true] 9524 — [nio-8090-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public void com.pie.controller.PieController.test(java.lang.String)],@PostMapping(value=»/pie/test») public void test(@RequestBody String eventMessage) < System. out .println("Here is the test String from Camunda: "+eventMessage); >,@ryans58: Thanks for your response Ryan. Could you please elaborate on $? I did not quite get it. I am just trying to send a string in the payload

Answer by Paislee Moody

The InputStream that contains the request body is read from the ServletRequest . If you dive deeper into ServletRequest class, you will notice that it has two methods among others:,That’s why during the second attempt to read the input stream we see a failure that the request body is missing.,This is shown in the code below — using the method logPostOrPutRequestBody we are able to read the InputStream from HttpServletRequest and log it to standard output.

However, the returned response is 5xx — Internal Server Error , and if you explore the standard output of the application, you will notice the following exception:

DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

The InputStream that contains the request body is read from the ServletRequest . If you dive deeper into ServletRequest class, you will notice that it has two methods among others:

Ideally, getReader should return a reader of your implementation of getInputStream( ), as shown below:

return new BufferedReader(new InputStreamReader(getInputStream()));

In this example we take the second approach, by first constructing an InputStream from the cached content:

final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bodyInStringFormat.getBytes());

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting HttpMessageNotReadableException after upgrading to 2.3.11.RELEASE #26959

Getting HttpMessageNotReadableException after upgrading to 2.3.11.RELEASE #26959

Comments

Previous Version: springCloudVersion = «Greenwich.RELEASE» springBootVersion = «2.1.13.RELEASE»

Upgraded Version: springCloudVersion = «Hoxton.SR3» springBootVersion = «2.3.11.RELEASE»

Spring Code:

 @RequestMapping(method = RequestMethod.POST, value = "valuemodified", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity processRequest(@RequestBody String jsonString)  

image

PostMan call:

Error After Upgrade:

 org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public TestController.processRequest(java.lang.String) at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:161) at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) 

Not sure why it broke after upgrade.
Things which I have tried after going through github issues and stackoverflow:

  1. Tried using postmapping instead of request mapping.
  2. Used different mediatypes But none worked.

The text was updated successfully, but these errors were encountered:

Источник

Оцените статью