回答

收藏

如何使用 cURL 发布 JSON 数据?

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

我使用 Ubuntu 并安装在上面cURL。我想用 cURL 测试我的 Spring REST 应用程序。我在 Java 端写了我的 POST 代码。但是,我想用 cURL 测试它。我正在尝试发布 JSON 数据。示例数据如下:
; L* E, V  k+ G" [
    {"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}6 l$ f; W' V. |$ v% d4 Z& |3 ?
我用这个命令:
  P1 U$ @! g+ m" q
    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* W* B2 T( S: e$ F; O" A& @3 T- |
回到这个错误:
# |+ K1 `# A* {  E# G7 {
    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
    ( ]0 `2 O' B& w5 |) B, }- }5 n9 }
错误描述如下:2 `) ~  S4 |+ O# h0 C5 [7 I' T
由于请求实体的格式不受请求方法 () 请求资源的支持,服务器拒绝了此请求。( ]( ], Z: T, G
Tomcat 日志:“POST /ui/webapp/conf/clear HTTP/1.1”415 10518 y' r& R" t* ^( d. y/ K: l
cURL 命令的正确格式是什么?4 T2 C7 O4 X7 I" n- B# C+ V/ t% ]! l
这是我的 Java 端PUT代码(我已经测试GET 和 DELETE 他们可以工作):
/ B# R' P0 x, N" v% p+ w! Y+ k
    @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;}
    1 C  r5 O. \  C- i
               - W1 g: f! f) {( e- k# E& Q
    解决方案:                                                               
, a2 G) q, M* v0 l                                                                您需要将内容类型设置为 application/json。但是-d(或--data)发送 Content-Type application/x-www-form-urlencoded,这在 Spring 方面是不被接受的。+ @) F# I, N6 ^* b) J) A. D2 Y
查看curl 手册页,我想你可以用-H(或--header):
( O" S+ h2 w. Y$ j& g7 l) @* F
    -H "Content-Type: application/json"/ l, ]- ?( M; O7 u2 s) V$ K
完整示例:
! V3 N& K: Y* U$ F1 {: C  P3 b
    curl --header "Content-Type: application/json" \  --request POST \  --data '{"username":"xyz","password":"xyz"}' \  http://localhost:3000/api/login" ~: x% j$ `+ l3 r3 X
(-H是--header,-d的缩写--data)0 Y" Y2 S# h9 y: _$ J/ P
请注意,如果你使用它,这个-request POST是可选-d的,因为该-d标志意味着 POST 请求。7 P8 n- \( i2 A3 g
在 Windows 上,情况略有不同。请参阅评论线程。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则