回答

收藏

如何使用 cURL 发布 JSON 数据?

技术问答 技术问答 553 人阅读 | 0 人回复 | 2023-09-11

我使用 Ubuntu 并安装在上面cURL。我想用 cURL 测试我的 Spring REST 应用程序。我在 Java 端写了我的 POST 代码。但是,我想用 cURL 测试它。我正在尝试发布 JSON 数据。示例数据如下:: L0 x8 J( X4 A, r
    {"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
    1 V8 C9 N% {5 E( V8 }: R& D! \
我用这个命令:6 w0 g, f6 n7 k" q1 p
    curl -i \    -H "Accept: application/json" \    -H "X-HTTP-Method-Override: PUT" \    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \    http://localhost:8080/xx/xxx/xxxx
    9 ]! S3 a4 P" m! S
回到这个错误:; O: k( l2 G" s: X6 m
    HTTP/1.1 415 Unsupported Media TypeServer: Apache-Coyote/1.1Content-Type: text/html;charset=utf-8Content-Length: 1051Date: Wed,24 Aug 2011 08:50:17 GMT
    : u2 d, t$ u# `" n
错误描述如下:$ f5 g  T$ w9 O# f* B9 j2 n. I
由于请求实体的格式不受请求方法 () 请求资源的支持,服务器拒绝了此请求。0 n  I1 m& S1 u+ |( _$ W1 g4 M7 N
Tomcat 日志:“POST /ui/webapp/conf/clear HTTP/1.1”415 10513 G; S9 H+ D$ m; h- a
cURL 命令的正确格式是什么?
" f# W) d& r3 o这是我的 Java 端PUT代码(我已经测试GET 和 DELETE 他们可以工作):5 v  @2 q  E- S. h* r$ F5 h
    @RequestMapping(method = RequestMethod.PUT)public Configuration updateConfiguration(HttpServletResponse response,@RequestBody Configuration configuration) { //consider @Valid tag    configuration.setName(&quotUT worked");   todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);    return configuration;}* j( F- k# e3 j3 n. S+ H
               . r, j6 q8 M  Z' Y, u9 T
    解决方案:                                                               
' M: Y$ v0 u& n  i- m                                                                您需要将内容类型设置为 application/json。但是-d(或--data)发送 Content-Type application/x-www-form-urlencoded,这在 Spring 方面是不被接受的。
+ j1 c# O# S9 P' C查看curl 手册页,我想你可以用-H(或--header):
( h8 W9 _: \; v/ b
    -H "Content-Type: application/json"7 v: g7 k0 S& u2 l. p+ x* o
完整示例:
- \" T" w% R) Q) Z
    curl --header "Content-Type: application/json" \  --request POST \  --data '{"username":"xyz","password":"xyz"}' \  http://localhost:3000/api/login4 N3 R+ d, y+ [
(-H是--header,-d的缩写--data)# Y& t! [0 X8 V$ K  r- U( e/ ~
请注意,如果你使用它,这个-request POST是可选-d的,因为该-d标志意味着 POST 请求。* N+ P& ]' x% f# p' {. U8 \1 y  g
在 Windows 上,情况略有不同。请参阅评论线程。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则