Issue
I have a @RestController with an endpoint that receives a single String :
@RestController
public class ScriptController {
private Logger logger = LoggerFactory.getLogger(ScriptController.class);
public ScriptController(Engine engine) {
this.engine = engine;
}
@RequestMapping(value = "/run", method = RequestMethod.POST)
public Object run(@RequestBody String script){
return engine.run(script);
}
}
when I send a request to this endpoint using CURL :
curl --request POST localhost:9999/run --data-binary "testObj.hi()"
I am not receiving the exact String ("testObj.hi()"
) in the Controller, instead I receive the following one :
testObj.hi%28%29=
what is the problem?
when I change the method from POST
to GET
(in both sides) it works! but I want to use POST
method.
Solution
By default, the request body is URL encoded in HTTP requests, and since there is no content-type header, spring boot doesn't decode the encoded characters.
Specifying Content-Type
header will solve the problem, something like this:
curl --request POST localhost:8080/run --data-binary "testObj.hi()" -H 'Content-Type: text/utf-8'
It works in case of GET requests because parameters are expected to be URL encoded in case of GET request and they are decoded by the spring.
Answered By - Saheb