curl common usage

处理 url 中包含的 shell 保留符号

请求 url 经常包含字符 &,该字符在 shell 中又有特殊含义。若不做任何处理,执行命令就会报错。最简单高效的办法就是用英文单/双引号把 url 包起来。

1
> curl -X GET "http://api.kl.me/works/5627?title=test&author=kl"

请求一个网页

1
> curl http://www.baidu.com

其实发送的就是 GET 请求。

请求时指定 request method,添加自定义首部

1
2
3
4
> curl -X GET http://api.kl.me/works/5627 \
> -H "X-Request-ID: uuid-01" \
> -H "Authorization: Bearer 3df3ffge92" \
> -H "Accept: application/vnd.heroku+json; version=3"

注意,request method 必须大写。

请求时以 json 对象为 request body

  1. 通过 -d 选项指定要提交的数据。适合较小的 json 对象。

    1
    2
    3
    4
    > curl -k -X PUT "https://api.kl.me/files/566fc93fc9e77c000bf07a7c" \
    > -H "X-Request-ID: uuid-1000" \
    > -H "Content-Type: application/json;charset=UTF-8" \
    > -d '{"hash": "hash_val"}'
  2. 提交从文件中读取的 json 数据。@ 符号后面紧跟文件路径

    1
    2
    3
    4
    > curl -k -X PUT "https://api.kl.me/files/566fc93fc9e77c000bf07a7c" \
    > -H "X-Request-ID: uuid-1000" \
    > -H "Content-Type: application/json;charset=UTF-8" \
    > -d @/home/kl/new_user.json

发送https请求,排查证书问题

发送https请求:

1
2
3
4
5
6
7
8
9
> curl -X GET https://api.kl.me/v1.0/shares/works/5627 \
> -H "X-Request-ID: uuid-01"

curl: (60) SSL certificate problem: Invalid certificate chain
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, ...
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.

https请求失败,但又看不到有用信息时,–verbose有助于排查问题

1
2
3
4
5
6
7
8
9
10
11
> curl -X GET https://api.kl.me/v1.0/shares/works/5627 \
> -H "X-Request-ID: uuid-01" --verbose

* Hostname was NOT found in DNS cache
* Trying 120.55.148.102...
* Connected to test.api.playplus.me (120.55.148.102) port 443 (#0)
* SSL certificate problem: Invalid certificate chain
* Closing connection 0
curl: (60) SSL certificate problem: Invalid certificate chain
More details here: http://curl.haxx.se/docs/sslcerts.html
...

根据输出信息猜测应该是请求中的域名与证书中的域名不匹配导致的。修改域名后再次请求,妥了。

关掉https请求过程中的证书校验

1
2
3
4
5
6
7
8
# 方法一
> curl -X GET https://api.kl.me/v1.0/shares/works/5627 -k

# 方法二
> curl -X GET https://api.kl.me/v1.0/shares/works/5627 --insecure

# 方法三 使用wget
> wget 'https://api.kl.me/v1.0/shares/works/5627' --no-check-certificate

参考资源

curl命令选项详解

0%