卷曲不适用于HTTP Post到Spring-data-rest RequestMapping

时间:2016-06-16 02:54:27

标签: java spring spring-mvc curl spring-restcontroller

我在弹簧RequestMapping中设置了@Controller,我无法正确发送CURL请求。尝试发送各种方法时,我一直收到HTTP 400返回码。我不确定设置错误。

这是请求

curl -v -X POST localhost:8082/api/registerDevice -d '{"serial":"FA541YJ05065"}' -H "Content-Type:application/json;charset=UTF-8"

这是输出

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying ::1...
* Connected to localhost (::1) port 8082 (#0)
> POST /api/registerDevice HTTP/1.1
> Host: localhost:8082
> User-Agent: curl/7.49.0
> Accept: */*
> Content-Type:application/json;charset=UTF-8
> Content-Length: 23
>
* upload completely sent off: 23 out of 23 bytes
< HTTP/1.1 400 Bad Request
< Server: Apache-Coyote/1.1
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 16 Jun 2016 02:48:50 GMT
< Connection: close
<
{"timestamp":1466045330556,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read document: Unexpected character (''' (code 39)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@3bae0839; line: 1, column: 2]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@3bae0839; line: 1, column: 2]","path":"/api/registerDevice"}* Closing connection 0

Spring RequestMapping

 @RequestMapping(value = "registerDevice", method = RequestMethod.POST)
  public ResponseEntity<String> registerDevice(@RequestBody Map<String, Object> payload) throws Exception {

更新

如下所述,这是一个转义引号并与Windows相关的问题。相同的CURL命令在centos上运行良好。

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{"""serial""":"""FA541YJ05065"""}" http://localhost:8082/api/deregisterDevice

On Centos

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"serial":"FA541YJ05065"}' http://localhost:8082/api/registerDevice

2 个答案:

答案 0 :(得分:0)

这背后的唯一原因是您的请求格式不正确 有关详细信息,请查看此Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how to get it right once for all?

答案 1 :(得分:0)

我怀疑你最终在json的开头发送了'。您可以尝试在json周围使用双引号并在其中转义它们。 See also

curl -v -X POST localhost:8082/api/registerDevice -d "{\"serial\":\"FA541YJ05065\"}" -H "Content-Type:application/json;charset=UTF-8"