掘金 后端 ( ) • 2024-04-17 09:51

curl

简介

cURL是一个利用URL语法在命令行下工作的文件传输工具,用来请求 Web 服务器。

常用示例

  • 查看网页源码 curl www.sina.com
  • 保存到文件 curl -o sina.html www.sina.com
  • 显示显示http response头信息 curl -i www.sina.com
  • 只显示头信息,不显示内容 curl -I www.sina.com
  • 显示通信过程 curl -v www.sina.com
  • 更详细的过程 curl --trace output.txt www.sina.com
  • GET方法 curl example.com/form.cgi?data=xxx&aa=xx
  • POST方法 curl -X POST --data "data=xxx" example.com/form.cgi
  • User Agent字段 curl --user-agent "[User Agent]" [URL]
  • cookie curl --cookie "name=xxx" www.example.com
  • 添加头信息 curl --header "Content-Type:application/json" http://example.com
  • 认证 curl --user name:password example.com
  • 添加解析 curl http://www.example.com --resolve www.example.com:80:127.0.0.1 --resolve www.example.com:443:127.0.0.1
  • 跳过证书检测 curl -k https://www.example.com
$ curl  -H 'Content-Type: application/json' -X POST http://localhost:1055/v1/api/notify/ -d '{"hostname":"xcx"}'

$ curl -XPOST $server/nlb?Action=CreateLoadBalancer&Version=2017-12-05 \
    -H 'Content-Type: application/json' \
    -H 'X-Product-Id: xx' \
    -d '{
         "name": "xx",
         "Description": "xx",
      }'
  • 指定打印信息内容
# time_namelookup:DNS 域名解析的耗时
# time_connect:TCP 连接建立的时间,就是三次握手的时间
# time_appconnect:SSL/SSH 等上层协议建立连接的时间,比如 connect/handshake 的时间
# time_redirect:从开始到最后一个请求事务的时间
# time_pretransfer:从请求开始到响应开始传输的时间
# time_starttransfer:从请求开始到第一个字节将要传输的时间
# time_total:这次请求花费的全部时间
$ cat curl-format.txt
    time_namelookup:  %{time_namelookup}\n
       time_connect:  %{time_connect}\n
    time_appconnect:  %{time_appconnect}\n
      time_redirect:  %{time_redirect}\n
   time_pretransfer:  %{time_pretransfer}\n
 time_starttransfer:  %{time_starttransfer}\n
                    ----------\n
         time_total:  %{time_total}\n
#-w:从文件中读取要打印信息的格式
#-o /dev/null:把响应的内容丢弃,因为我们这里并不关心它,只关心请求的耗时情况
#-s:不要打印进度条
$ curl -w "@curl-format.txt" -o /dev/null -s https://www.baidu.com
    time_namelookup:  0.002
       time_connect:  0.012
    time_appconnect:  0.037
      time_redirect:  0.000
   time_pretransfer:  0.037
 time_starttransfer:  0.049
                    ----------
         time_total:  0.049

Screen-Shot-2018-10-16-at-14.51.29-1.png

一个实用的curl脚本,帮助我们更好的分析链路耗时情况

#!/bin/bash
#
# curl wrapper returning timing information.
#
# curl format adapted from
#  http://josephscott.org/archives/2011/10/timing-details-with-curl/
#
# Example usage:
#   $ curlt http://www.apple.com
#   $ time curlt http://www.apple.com -v

set -e

curl_format='{
 "time_namelookup": %{time_namelookup},
 "time_connect": %{time_connect},
 "time_appconnect": %{time_appconnect},
 "time_pretransfer": %{time_pretransfer},
 "time_redirect": %{time_redirect},
 "time_starttransfer": %{time_starttransfer},
 "time_total": %{time_total}
}'

exec curl -w "$curl_format" -o /dev/null -s "$@"