The request sent by the client was syntactically incorrect ().+Spring , RESTClient

心已入冬 提交于 2019-12-01 03:53:58

Try this

Change

@RequestParam("json") String json

To

 @RequestBody Task task

If you are not interested in POST method you can try this

change your Controller method from

@RequestMapping(value = "/addTask", method = RequestMethod.GET)
   public ModelAndView addTask(@RequestParam("json") String json)

to

@RequestMapping(value = "/addTask/{taskName}/{taskId}/{taskDesc}", method = RequestMethod.GET)
   public ModelAndView addTask(@RequestParam("taskName") String taskName,
@RequestParam("taskId") String taskId,@RequestParam("taskDesc") String taskDesc)

and change your URL to

http://localhost:8080/Prime/addTask/mytask/233/testDesc
Ben Iggulden

I ran into a similar situation using a JSON string in the request body recently, and using a very similar Spring setup as yours. In my case I wasn't specifying a String parameter and deserialising it myself though, I was letting Spring do that:

   @RequestMapping(value = "/myService/{id}", method = RequestMethod.POST)
   @ResponseBody
   public void myService(@PathVariable(value = "id") Long id, @RequestBody MyJsonValueObject request) {
   ..
   }

I was getting an HTTP error 400 "The request sent by the client was syntactically incorrect" response. Until I realised that there wasn't a default constructor on the @RequestBody MyJsonValueObject so there were problems deserialising it. That problem presented in this way though.

So if you are using POST and objects, and getting errors like this, make sure you have a default constructor! Add some JUnit to be sure you can deserialise that object.

Note: I'm not saying this is the only reason you get this error. The original case used just String (which does have a default constructor !) so it's a little different. But in both cases it appears the request URI appears to have been mapped to the right method, and something has gone wrong trying to extract parameters from the HTTP request.

My problem was due to the incorrect mapping of the @RequestBody object.

My Request Body looks like this

{data: ["1","2","3"]}

I had the following code in my controller

@RequestMapping(value = "/mentee", method = RequestMethod.POST)
public @ResponseBody boolean updateData(@RequestBody List<Integer> objDTO, HttpSession session) {
        ...
    }

This give me HTTP 400 because Spring doesn't know how to bind my Json data to a List.

I changed the RequestBody object to the following

@RequestMapping(value = "/mentee", method = RequestMethod.POST)
public @ResponseBody boolean updateData(@RequestBody ObjectiveDto objDTO, HttpSession session) {
        ...
    }

and defined ObjectiveDto as followed

@ToString
public class ObjectiveDto {

    @Getter @Setter
    private List<Integer> data;

}

This resolved the HTTP 400 error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!