一个计算机技术爱好者与学习者

0%

好好学Linux:curl命令

1. curl简介

curl命令始于1998年,是一个命令行工具和库,用于通过 URL 传输数据。
curl几乎支持所有协议类型的数据传输,HTTP、HTTPS、FTP、SFTP、SMB、TELNET等等等等。
对于开发者而言,curl最常见的用途是代替浏览器或者postman等接口测试工具,用来请求接口并获取数据。

更多内容参考curl官网

2. curl参数说明

curl命令的参数很多,这里我们对一些常用参数进行说明。

  • X:指定请求类型,GET、POST、PATCH、DELETE、PUT等
  • s:不输出错误和进度
  • H:设置header内容
  • d:设置body内容
  • d@:设置body内容,从文件读取
  • F:请求时带文件
  • m:请求超时时间
  • k:忽略SSL证书验证
  • o:保存文件

3. curl实践

3.1. curl不输出错误和进度

1
2
3
4
5
6
# 不输出错误和进度
curl -s "https://www.voidking.com"
curl -sX GET "https://www.voidking.com"

# 不产生任何输出
curl -s -o /dev/null "https://www.voidking.com"

更多内容参考 curl的用法指南

3.2. curl post请求带参数

1、application/x-www-form-urlencoded请求:

1
2
3
id=1
ip=10.0.0.1
curl -X POST "http://rap2api.taobao.org/app/mock/241888/updateip" -d "id=${id}&ip=${ip}"

2、application/json请求:

1
2
3
4
5
curl -X POST "http://rap2api.taobao.org/app/mock/241888/updateip" -H "Content-type: application/json" -d '{"id":"'${id}'","ip":"'${ip}'"}' 
# or
curl -X POST "http://rap2api.taobao.org/app/mock/241888/updateip" -H "Content-type: application/json" -d@data.json
# data.json是大文件
curl -X POST "http://rap2api.taobao.org/app/mock/241888/updateip" -H "Content-type: application/json" -H "Expect:" -d@data.json

其中data.json中的内容为:

1
2
3
4
{
"id":1,
"ip":"10.0.0.1"
}

3、multipart/form-data请求:

1
curl -X POST http://rap2api.taobao.org/app/mock/241888/updateip -F "id=${id}" -F "filename=@file.tar.gz"

3.3. curl设置超时

1
curl -m 15 -s "https://www.voidking.com"

3.4. curl忽略证书验证

执行curl命令时,如下报错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
curl: (60) SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
of Certificate Authority (CA) public keys (CA certs). The default
bundle is named curl-ca-bundle.crt; you can specify an alternate file
using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.

解决办法:如报错提示,使用 -k 参数

1
curl -k "https://www.voidking.com"

3.5. curl下载文件

1
curl -o icon.png "https://www.python.org/static/opengraph-icon-200x200.png"

curl下载这种方法也可以用来解决curl报错:curl: (23) Failed writing body (4096 != xxx)

1
curl -o /dev/null -s -w "%{http_code}\n" -X GET http://example.com
  • 本文作者: 好好学习的郝
  • 原文链接: https://www.voidking.com/dev-linux-curl/
  • 版权声明: 本文采用 BY-NC-SA 许可协议,转载请注明出处!源站会即时更新知识点并修正错误,欢迎访问~
  • 微信公众号同步更新,欢迎关注~