回答

收藏

如何使用 cURL 发布 JSON 数据?

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

我使用 Ubuntu 并安装在上面cURL。我想用 cURL 测试我的 Spring REST 应用程序。我在 Java 端写了我的 POST 代码。但是,我想用 cURL 测试它。我正在尝试发布 JSON 数据。示例数据如下:
$ G4 ?5 \2 P$ k% }3 ^
    {"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}
    8 S' P% M3 k9 S+ d7 p5 N5 {- D
我用这个命令:
- s, f% W' P; B* U+ r
    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
    / L4 G) h7 F7 K% U! F+ ]2 r1 Z
回到这个错误:
: X$ o: N; y6 {6 a0 D, R6 s) T
    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 GMT6 u8 v8 H) ~! P
错误描述如下:
1 @2 G5 |- z9 ~8 J* v4 p' @/ S由于请求实体的格式不受请求方法 () 请求资源的支持,服务器拒绝了此请求。
* B9 `8 Y* ^1 P9 ^3 ^
Tomcat 日志:“POST /ui/webapp/conf/clear HTTP/1.1”415 1051" c8 W) X. _8 s3 ]* Z
cURL 命令的正确格式是什么?
- X- R  {* R$ T3 m2 r6 f  F. V这是我的 Java 端PUT代码(我已经测试GET 和 DELETE 他们可以工作):/ s& D9 p; y" k8 Q( c
    @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;}
    ) M0 Q$ d5 R) A5 \0 w
               ; K5 A! Y) n" a0 n) H" ]
    解决方案:                                                               
3 B% S5 {6 P- B) R0 j: A, `                                                                您需要将内容类型设置为 application/json。但是-d(或--data)发送 Content-Type application/x-www-form-urlencoded,这在 Spring 方面是不被接受的。
* I; I: g( V. T0 R; S, V查看curl 手册页,我想你可以用-H(或--header):* b5 u7 g# F2 g
    -H "Content-Type: application/json". X' v6 @% \: E5 f8 {4 Z: Y
完整示例:
) }0 P1 R8 d0 f  f
    curl --header "Content-Type: application/json" \  --request POST \  --data '{"username":"xyz","password":"xyz"}' \  http://localhost:3000/api/login9 v  Q: R# [5 p: M0 k' b, ]
(-H是--header,-d的缩写--data)
3 y$ w, @4 Q# k  k9 u请注意,如果你使用它,这个-request POST是可选-d的,因为该-d标志意味着 POST 请求。' n  P# L* v; B* w& D3 H1 W
在 Windows 上,情况略有不同。请参阅评论线程。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则