cURL – POST请求示例

cURL徽标

一些cURL POST请求示例供自参考。

1.普通POST

1.1无需数据即可开机自检

$ curl -X POST http://localhost:8080/api/login/

1.2使用数据进行POST。

$ curl -d "username=mkyong&password=abc" http://localhost:8080/api/login/

1.3 Spring REST接受普通的POST数据。

@PostMapping("/api/login")
    public ResponseEntity<?> login(@RequestParam("username") String username,
                                    @RequestParam("password") String password) {
        //...
    }

    @PostMapping("/api/login")
    public ResponseEntity<?> login(@ModelAttribute Login login) {
        //...
    }

2. POST +多部分

要使用文件进行POST,请添加此-F file=@"path/to/data.txt"

2.1上传文件

$ curl -F file=@"path/to/data.txt" http://localhost:8080/api/upload/

2.2上载带有额外字段的多个文件:

$ curl -F extraField="abc" -F files=@"path/to/data.txt" -F files=@"path/to/data2.txt"  http://localhost:8080/api/upload/multi/

2.3 Spring REST接受POST Multipart数据。

@PostMapping("/api/upload")
    public ResponseEntity<?> uploadFile(
            @RequestParam("file") MultipartFile uploadfile) {
        //...
    }
	
    @PostMapping("/api/upload/multi")
    public ResponseEntity<?> uploadFiles(
            @RequestParam("extraField") String extraField,
            @RequestParam("files") MultipartFile[] uploadfiles) {
        //...
    }
	
    @PostMapping("/api/upload/multi2")
    public ResponseEntity<?> uploadFiles2(
            @ModelAttribute UploadModel model) {
        //...
    }

3. POST + JSON

要使用JSON数据进行POST,请添加此-H "Content-Type: application/json"

3.1在Windows上,转义双引号

c:\> curl -H "Content-Type: application/json" -X POST -d {\"username\":\"mkyong\",\"password\":\"abc\"} http://localhost:8080/api/login/

3.2对于* nix或Mac OSX,请添加单引号

$ curl -H "Content-Type: application/json" -X POST -d '{"username":"mkyong","password":"abc"}' http://localhost:8080/api/login/

3.3 Spring REST接受POST JSON数据。

@PostMapping("/api/login")
    public ResponseEntity<?> login(@RequestBody Login login) {
        //..
    }

参考文献

  1. cURL官方网站
  2. 维基百科– cURL
  3. 使用Spring构建REST服务
  4. cURL –将JSON数据发布到Spring REST
  5. Spring Boot文件上传示例– Ajax和REST

翻译自: https://mkyong.com/spring/curl-post-request-examples/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值