本文用来记录一些 Curl 日常使用中的技巧和注意点,虽然现在大部分的调试软件或者工具提供了自动生成的代码的功能,但是在服务器上操作时,可以熟练掌握这些技巧可以快速的提高我们的工作效率。
Debug Related
- -v/–trace/–trace-ascii
可以用来展示请求的 protocol 和具体的请求和回复的内容
- –trace-time
从名字上便可以发现这个是用于统计请求的时间
$ curl --trace-ascii d.txt --trace-time http://example.com/
HOST
通常我们在使用域名访问的时候,一般是通过 DNS 或者/etc/hosts
文件中的定义自动解析的。当我们的域名还没有生效或者暂时未绑定对应服务器的 IP 时,可以通过--resolve
选项来指定。
$ curl --resolve www.example.org:80:127.0.0.1 http://www.example.org/
Proxy
可以在域名后面添加端口号,也可以使用通过 proxy 的方式来指定。
$ curl --proxy http://proxy.example.org:4321 http://remote.example.org
Username and password
$ curl -u user:password http://example.org/
Fetch page
正常情况下默认是 GET 的方式访问指定的目标网址,如果我们想看返回的目标地址的头部信息时,可以使用如下两个选项:
-i
连同 response 的 body 返回 header 相关的信息-I
只返回 header 相关的信息,方便用于调试
多个 URL 同时请求
curl 支持对具有相同请求参数的 URL 发起请求。比如:
$ bash http://url1.xxx.com http://url2.xxx.com
很多时候我们通常会对同一个 url 按照不同的请求方法去发起请求。比如一般先 POST 请求,后面再进行 GET 请求。 此时我们可以使用--next
的方式
$ curl -d score=10 http://example.com/post.cgi --next http://example.com/results.html
HTML Forms
Forms are the general way a website can present an HTML page with fields for the user to enter data in, and then press some kind of ‘OK’ or ‘Submit’ button to get that data sent to the server. The server then typically uses the posted data to decide how to act. Like using the entered words to search in a database, or to add the info in a bug tracking system, display the entered address on a map or using the info as a login-prompt verifying that the user is allowed to see what it is about to see.
GET
这个方式比较简单,可以类似于 url 的 query 请求方式。因为 GET 的方式会将所有的参数体现在 URL 中
$ curl "http://www.example.com/when/junk/birthday=1905&press=OK"
POST
使用 post 方法的 form data 请求方式有几个好处:
- 避免 URL 过长
- 避免一些敏感信息直接在 URL 中暴露
- 适用于需要传输较大内容或者无法阅读的 URL
需要注意的是 curl 请求一般不会对内容进行编码,而 formdata 的方式需要发送的数据一定是经过编码的。如果我们单纯的使用--data
来指定 formdata 参数时需要注意一些特殊符号的编码,比如空格需要改成%20
。
一般这种类型的 POST 请求的 Content-Type 需要指定为 application/x-www-form-urlencoded
在较新的 curl 版本中,可以通过--data-urlencode
的方式让 curl 帮助我们将编码完成。 当我们重复使用--data
选项时,curl 会自动将其使用&
符号将其合并起来。这一点方便在写脚本时的可阅读性。
$ curl --data-urlencode "name=I am Jesse" http://www.example.com
文件上传
当请求需要的是上传文件时,我们一般指定Content-type: multipart/form-data
。 不过在使用 curl 请求的时候,我们可以之间的通过如下的方式操作即可,相关的请求头 curl 会帮我们设置。
$ curl --form upload=@localfilename --form press=OK [URL]
这种方式可以比较方便的将本地文件直接作为 form data 的请求的一部分。
其实如果请求支持PUT
方法的话,此时可以使用--upload-file
的方式来上传。
$ curl --upload-file uploadfile http://www.example.com/upload
Location
一般 location 选项用于返回值的重定向。所以如果目标 URL 返回的是其他的地址时,可以增加这个选项--location
。
Cookies
一般的方式是使用--dump-header
存储 cookie,后续使用--cookie xxx_file
使用储存的 cookie。
也可以使用--cookie-jar
的方式来更新 cookie 文件.
$ curl --cookie cookies.txt --cookie-jar newcookies.txt http://example.com
HTTPS
可以使用--cert
来指定证书。
$ curl --cert mycert.pem https://secure.example.com
自定义
可以使用--headers
来自定义一些请求头。--request/-X
来指定请求方法。
一些技巧和选项
When using Curl in shell scripts, always pass-fsSL
, which:
- Treats non-2xx/3xx responses as errors (-f).
- Disables the progress meter (-sS).
- Handles HTTP redirects (-L).