spring-mvc The request sent by the client was syntactically incorrect. for json post - spring-mvc

I am trying to build a springmvc app. On one of the action I want it to take a POST of JSON content. I am sending the following values:
POST /TestResults/create.json HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
[ { "test_name": "value1", "test_time": "111"} ]
However, when I send it I am getting the following error:
The request sent by the client was syntactically incorrect.
My action looks like this:
#RequestMapping(value="/create", method=RequestMethod.POST, consumes = "application/json")
#ResponseBody
public ModelAndView createTest(#RequestBody TestResult test_result) {
When I change the action to bepublic ModelAndView createTest(#RequestBody String test_result) { the action does succeed but I am using "String" at that time.
Is it possible to know what I might be doing incorrectly?

The JSON you are receiving is a JSON array. A JSON array unless you have a custom deserializer cannot be mapped to a type like TestResult, unless it's some subtype of Collection. You'll want to use something like
public ModelAndView createTest(#RequestBody List<TestResult> testResults) {
For #RequestBody String it works because all Spring has to do is read from the request body and convert the bytes into a String.

Related

Spring 5 - Read JSON or MultipartFile

I ran into what looks like a really simple problem. I have an http endpoint which should accept either JSON body or uploaded file.
Here is definition of controller method:
#PostMapping(value = "/api/endpoint")
public CompletableFuture<ResponseEntity<Void>> createResource(
#RequestParam(name = "file", required = false) MultipartFile file,
#RequestBody(required = false) Command command){
}
Command is a POJO class with Jackson annotations for deserialisation.
When I pass JSON body with Content-Type: application/json, it works fine. But when I pass file with Content-Type: multipart/form-data, I get 415 Unsupported Media Type.
Here is raw http request when passing just JSON body.
POST /api/devices?= HTTP/1.1
Host: localhost:8080
Content-Type: application/json
cache-control: no-cache
{"foo": "bar"}------WebKitFormBoundary7MA4YWxkTrZu0gW--
Any ideas what is causing this, thanks.
Try the below code.
#PostMapping(value = "/api/endpoint",consumes = {"multipart/form-data"})
public CompletableFuture<ResponseEntity<Void>> createResource(
#RequestPart("file") MultipartFile file,
#RequestPart Command command){
}
You might need two separate methods with different parameters and annotations. Which, of course, can each just call a shared internal method for their common behaviors.

400 when passing url in #PathVariable to Spring MVC controller method

I'm trying to pass a url in to a Spring MVC controller method in a #PathVariable but am getting a 400 http response code, and the request is rejected before it reaches the controller method.
My request is being issued as:
curl 'https://127.0.0.1:8443//myapi/page/http%3A%2F%2Fwww.example.co.uk%2Ffolder%2Fpage_n0/info' -k -w "\nResponse code: %{http_code}\n"
The controller method, and UTF-8 filter, is:
#Bean
public FilterRegistrationBean filterRegistrationBean()
{
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
#RequestMapping(value = {"/myapi/page/{url}/info"}, method = RequestMethod.GET)
public ResponseEntity<?> test(HttpServletRequest request, HttpServletResponse response, #PathVariable("url") String webPage)
{
ResponseEntity<?> results = new ResponseEntity<Map<String, Object>>(HttpStatus.OK);
// Do something here
return results;
}
I am using Tomcat 8.5.5, and nothing is present in the log files (logging has been set at DEBUG level) except for the following entry in localhost_access_log.2016-10-04.txt:
127.0.0.1 - - [04/Oct/2016:09:04:24 +0100] "GET //myapi/page/http%/info HTTP/1.1" 400 -
In my test code, the url being passed into is being encoded using URLEncoder.encode(), so should be being encoded correctly.
In the remote debugger, I can see that the CharacterEncodingFilter registration code above is being entered so the filter should be being registered.
I have also addedURIEncoding="UTF-8" to each of the Connectors in the server.xml file in $CATALINA_HOME/conf.
I am going round in circles with this and keep on thinking there's something obvious I'm missing. I've never had any issues using a #PathVariable before so I presume I'm encountering some sort of encoding issue, probably relating to the % sign.
I'd be grateful for any help with this!
Update:
I think the issue is that Spring, inside AbstractHandlerMethodMapping and UriUtils, is decoding the entire url, including the #PathVariable portion. It then cannot find a request mapping for the decoded url which is unsurprising since the decoded url includes the decoded url in the #PathVariable. I need to find some way of telling Spring not to decode the application/x-www.form-urlencoded portion of the url.
Any ideas?

Does Spring #RequestBody support the GET method?

I am trying to carry JSON data in an HTTP GET request message, but my Spring MVC server can't seem to retrieve the JSON data from the GET request body.
HTTP's GET method does not include a request body as part of the spec. Spring MVC respects the HTTP specs. Specifically, servers are allowed to discard the body. The request URI should contain everything needed to formulate the response.
If you need a request body, change the request type to POST, which does include the request body.
Based on official info
https://docs.spring.io/spring-framework/docs/4.1.0.RC2/spring-framework-reference/html/mvc.html
#RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));
byte[] requestBody = requestEntity.getBody();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
In case anyone's here trying to get the OpenAPI generation to treat the fields of the request object as separate GET params, you'll want to use #ParameterObject (org.springdoc.api.annotations.ParameterObject) which was added here: https://github.com/springdoc/springdoc-openapi/issues/590

Spring MVC binding request parameters

I wrote a spring-mvc controller method to get an array of values in the request parameter.The method looks like below
/**
Trying to get the value for request param foo which passes multiple values
**/
#RequestMapping(method=RequestMethod.GET)
public void performActionXX(HttpServletRequest request,
HttpServletResponse response,
#RequestParam("foo") String[] foo) {
......
......
}
The above method works fine when the request url is in below format
...?foo=1234&foo=0987&foo=5674.
However when the request url is in below format the server returns 400 error
...?foo[0]=1234&foo[1]=0987&foo[2]=5674
Any idea how to fix the method to cater to the second format request url?
This is not possible with #RequestParam. What you can do is implement and register your own HandlerMethodArgumentResolver to perform to resolve request parameters like
...?foo[0]=1234&foo[1]=0987&foo[2]=5674
into an array. You can always checkout the code of RequestParamMethodArgumentResolver to see how Spring does it.
Note that I recommend you change how the client creates the URL.
The server is supposed to define an API and the client is meant to follow it, that's why we have the 400 Bad Request status code.
I resolved this issue using the request.getParameterMap().Below is code.
Map<String,String> parameterMap= request.getParameterMap();
for(String key :parameterMap.keySet()){
if(key.startsWith("nameEntry")){
nameEntryLst.add(request.getParameter(key));
}
}

ASP.NET MVC ignoring Content-Length?

I've been having some problems with missing post data in ASP.NET MVC which has lead me to investigate how ASP.NET MVC deals with invalid content lengths. I had presumed that a post with a invalid content length should be ignored by MVC.NET but this doesn't seem to be the case.
As an example, try creating a new ASP.NET MVC 2 web application and add this action to the HomeController:
public ActionResult Test(int userID, string text)
{
return Content("UserID = " + userID + " Text = " + text);
}
Try creating a simple form that posts to the above action, run fiddler and (using "Request Builder") modify the raw data so that some of the form data is missing (e.g. remove the text parameter). Before executing the request, remember to un-tick the "Fix Content-Length header" checkbox under the Request Builder options then set a break point on the code above and execute the custom http request.
I find that the request takes a lot longer than normal (30 seconds or so) but to my amazement is still processed by the controllers action. Does anyone know if this is expected behavior and, if so, what would you recommend to safeguard against invalid content-lengths?
ASP.NET does not ignore the Content-Length request header. Consider the following controller action as an example which simply echoes back the foo parameter:
[HttpPost]
public ActionResult Index(string foo)
{
return Content(foo, "text/plain");
}
Now let's make a valid POST request to it:
using (var client = new TcpClient("127.0.0.1", 2555))
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.Write(
#"POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 10
Connection: close
foo=foobar");
writer.Flush();
Console.WriteLine(reader.ReadToEnd());
}
As expected this prints the response HTTP headers (which are not important) and in the body we have foobar. Now try reducing the Content-Length header of the request:
POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 5
Connection: close
foo=foobar
Which returns a single f in the response body. So as you can see an invalid HTTP request could lead to incorrect parsing of the parameters.

Resources