1、传递JSON格式的参数
这是一个POST请求的接口,使用了@RequestBody注解。其接口的核心代码如下:
@RestController
@RequestMapping("blog")
public class BlogController {
@RequestMapping(value = "add", method = RequestMethod.POST)
Blog add(@RequestBody Blog blog) {
//业务逻辑代码...
return blog;
}
}
使用curl对该POST请求的接口进行测试,测试的url如下:
curl -d "{\"title\":\"test\"}" -H "Content-Type:application/json" http://localhost:8080/blog/add
这个url可以正常请求。但是如下的几种格式都不行:
curl -d '{"title":"test"}' -H "Content-Type:application/json" http://localhost:8080/blog/add
curl -d "{'title':'test'}" -H "Content-Type:application/json" http://localhost:8080/blog/add
curl -d '{\'title\':\'test\'}' -H "Content-Type:application/json" http://localhost:8080/blog/add
可以看出,通过curl传递JSON格式的参数仅仅只支持"{\"key\":\"value\"}"。这个结论使我浪费了较多时间。
2、GET请求包含中文参数
需要使用--data-urlencode进行编码,请求的url如下:
curl -G --data-urlencode "name=世界" http://localhost:8080/hello/say
这个接口的代码如下:
@RestController
@RequestMapping("hello")
public class HelloController {
@RequestMapping(value = "say", method = RequestMethod.GET)
public String sayHello(String name) {
return "Hello, " + name;
}
}
可以看到,此时后端如果没有对该参数进行解码,则会出现乱码。
3、POST请求包含中文参数
只使用--data-urlencode不好使,需要修改Content-Type为x-www-form-urlencoded。如下:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: */*" --data-urlencode "title=测试" http://localhost:8080/blog/add
可以看到,此时后端如果没有对该参数进行解码,则会出现乱码。
另外,如果是POST请求的JSON格式的参数包含中文字符,需要在Content-Type后再附加charset=GBK,否则将会出现Bad Request错误。如下:
curl -d "{\"title\":\"测试\"}" -H "Content-Type:application/json" http://localhost:8080/blog/add
curl -d "{\"title\":\"测试\"}" -H "Content-Type:application/json;charset=GBK" http://localhost:8080/blog/add