使用CURL POST参数

https://davidwalsh.name/curl-post-file

POSTing Form Data with cURL

Start your cURL command with curl -X POST and then add -F for every field=value you want to add to the POST:

curl -X POST -F 'username=davidwalsh' -F 'password=something' http://domain.tld/post-to-me.php

If you were using PHP, you could use print_r on the $_POST variable to see that your server received the POST data as expected:

Array(
  'username' => 'davidwalsh',
  'password' => 'something'
)

If you need to send a specific data type or header with cURL, use -H to add a header:

# -d to send raw data
curl -X POST -H 'Content-Type: application/json' -d '{"username":"davidwalsh","password":"something"}' http://domain.tld/login

POSTing Files with cURL

POSTing a file with cURL is slightly different in that you need to add an @ before the file location, after the field name:

curl -X POST -F 'image=@/path/to/pictures/picture.jpg' http://domain.tld/upload

Using PHP to explore the $_FILES variable array would show file data as though it was uploaded via a form in browser:

Array(
  "image": array(
    "name" => "picture.jpg"
    "type" => "image/jpeg",
    "tmp_name" => "/path/on/server/to/tmp/phprj5rkG",
    "error" => 0,
    "size" => 174476
  )
)

POSTing file contents with cURL is Probably easier than you thought, right?

The first time I needed to POST file data from command line I thought I was in for a fight; instead I found that cURL made the process easy!

### 如何使用 `curl` 发送带参数POST 请求 发送带有参数POST 请求可以通过 `-d` 或 `-F` 选项实现。以下是详细的说明: #### 使用 `-d` 参数传递表单数据 当需要发送简单的键值对作为 POST 数据时,可以使用 `-d` 选项。多个键值对可以用 `&` 符号连接。 ```bash curl -X POST -d 'username=admin&password=123456' http://example.com/login ``` 此命令向目标 URL (`http://example.com/login`) 发送了一个 POST 请求,并携带了两个参数:`username` 和 `password`[^2]。 如果需要自定义请求头(例如设置 Content-Type),可以在命令中加入 `-H` 选项: ```bash curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=admin&password=123456' http://example.com/login ``` 这表明我们正在发送的是 URL 编码的数据流[^2]。 #### 使用 JSON 格式的 POST 请求 对于现代 API 接口,通常更倾向于接收 JSON 格式的数据。此时需要显式声明 `Content-Type` 并提供合法的 JSON 字符串。 ```bash curl -X POST -H "Content-Type: application/json" -d '{"username": "admin", "password": "123456"}' http://example.com/api/authenticate ``` 这条命令设置了请求的内容类型为 JSON,并将用户名和密码封装成 JSON 对象后提交给服务器[^2]。 #### 文件上传功能 某些场景下可能还需要上传文件至服务端,则可借助 `-F` 来完成这一操作。注意,在指定本地路径前要加上 `@` 符号表示读取实际文件内容而非字符串本身。 ```bash curl -X POST -F 'file=@/path/to/local/file.txt' http://example.com/upload ``` 这里展示了如何把名为 `/path/to/local/file.txt` 的文档上传到远程地址上去[^2]。 以上就是几种常见的通过 curl 工具发起包含不同种类负载体在内的 HTTP POST 方法调用的方式介绍。 ### 注意事项 - 如果涉及敏感信息比如账号密码之类的字段建议采用 HTTPS 协议加密通信来保障信息安全; - 部分老旧版本或者特定配置下的 web server 可能不完全兼容所有的 content-type 定义,请视具体情况调整相应头部设定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值