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

Curl not working for HTTP Post to Spring-data-rest RequestMapping

我在 spring @Controller 中有一个 RequestMapping 设置,但我无法向它正确发送 CURL 请求。尝试发送各种方式时,我不断收到 HTTP 400 return 代码。我不确定什么设置不正确。

这是请求

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(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

在 Centos 上

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

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

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

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