文章目录

  • 前言
  • 一、curl介绍
  • 二、具体使用
    • 1.当前目录新建文件
    • 2.执行命令
    • 3.结果
  • 总结

前言

系统需求中需要请求第三方数据接口获取数据,那线上请求第三方接口耗时多少?今天给大家分享一个干货编程小技巧, 得此利器,事半功倍,它就是curl。


一、curl介绍

  • 一般线上系统默认安装
curl -Vcurl 7.29.0 (x86_64-redhat-linux-gnu) libcurl/7.29.0 NSS/3.53.1 zlib/1.2.7 libidn/1.28 libssh2/1.8.0
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz unix-sockets
  • curl可选参数,使用curl --help查看
[valley@online003 ~]$ curl --help
Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only--anyauth       Pick "any" authentication method (H)-a, --append        Append to target file when uploading (F/SFTP)--basic         Use HTTP Basic Authentication (H)--cacert FILE   CA certificate to verify peer against (SSL)--capath DIR    CA directory to verify peer against (SSL)-E, --cert CERT[:PASSWD] Client certificate file and password (SSL)--cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)--ciphers LIST  SSL ciphers to use (SSL)--compressed    Request compressed response (using deflate or gzip)-K, --config FILE   Specify which config file to read--connect-timeout SECONDS  Maximum time allowed for connection-C, --continue-at OFFSET  Resumed transfer offset-b, --cookie STRING/FILE  String or file to read cookies from (H)-c, --cookie-jar FILE  Write cookies to this file after operation (H)--create-dirs   Create necessary local directory hierarchy--crlf          Convert LF to CRLF in upload--crlfile FILE  Get a CRL list in PEM format from the given file-d, --data DATA     HTTP POST data (H)--data-ascii DATA  HTTP POST ASCII data (H)--data-binary DATA  HTTP POST binary data (H)--data-urlencode DATA  HTTP POST data url encoded (H)--delegation STRING GSS-API delegation permission--digest        Use HTTP Digest Authentication (H)--disable-eprt  Inhibit using EPRT or LPRT (F)--disable-epsv  Inhibit using EPSV (F)-D, --dump-header FILE  Write the headers to this file--egd-file FILE  EGD socket path for random data (SSL)--engine ENGINGE  Crypto engine (SSL). "--engine list" for list-f, --fail          Fail silently (no output at all) on HTTP errors (H)-F, --form CONTENT  Specify HTTP multipart POST data (H)--form-string STRING  Specify HTTP multipart POST data (H)--ftp-account DATA  Account data string (F)--ftp-alternative-to-user COMMAND  String to replace "USER [name]" (F)--ftp-create-dirs  Create the remote dirs if not present (F)--ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)--ftp-pasv      Use PASV/EPSV instead of PORT (F)-P, --ftp-port ADR  Use PORT with given address instead of PASV (F)--ftp-skip-pasv-ip Skip the IP address for PASV (F)--ftp-pret      Send PRET before PASV (for drftpd) (F)--ftp-ssl-ccc   Send CCC after authenticating (F)--ftp-ssl-ccc-mode ACTIVE/PASSIVE  Set CCC mode (F)--ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F)-G, --get           Send the -d data with a HTTP GET (H)-g, --globoff       Disable URL sequences and ranges using {} and []-H, --header LINE   Custom header to pass to server (H)-I, --head          Show document info only-h, --help          This help text--hostpubmd5 MD5  Hex encoded MD5 string of the host public key. (SSH)-0, --http1.0       Use HTTP 1.0 (H)--ignore-content-length  Ignore the HTTP Content-Length header-i, --include       Include protocol headers in the output (H/F)-k, --insecure      Allow connections to SSL sites without certs (H)--interface INTERFACE  Specify network interface/address to use-4, --ipv4          Resolve name to IPv4 address-6, --ipv6          Resolve name to IPv6 address-j, --junk-session-cookies Ignore session cookies read from file (H)--keepalive-time SECONDS  Interval between keepalive probes--key KEY       Private key file name (SSL/SSH)--key-type TYPE Private key file type (DER/PEM/ENG) (SSL)--krb LEVEL     Enable Kerberos with specified security level (F)--libcurl FILE  Dump libcurl equivalent code of this command line--limit-rate RATE  Limit transfer speed to this rate-l, --list-only     List only names of an FTP directory (F)--local-port RANGE  Force use of these local port numbers-L, --location      Follow redirects (H)--location-trusted like --location and send auth to other hosts (H)-M, --manual        Display the full manual--mail-from FROM  Mail from this address--mail-rcpt TO  Mail to this receiver(s)--mail-auth AUTH  Originator address of the original email--max-filesize BYTES  Maximum file size to download (H/F)--max-redirs NUM  Maximum number of redirects allowed (H)-m, --max-time SECONDS  Maximum time allowed for the transfer--metalink      Process given URLs as metalink XML file--negotiate     Use HTTP Negotiate Authentication (H)-n, --netrc         Must read .netrc for user name and password--netrc-optional Use either .netrc or URL; overrides -n--netrc-file FILE  Set up the netrc filename to use-N, --no-buffer     Disable buffering of the output stream--no-keepalive  Disable keepalive use on the connection--no-sessionid  Disable SSL session-ID reusing (SSL)--noproxy       List of hosts which do not use proxy--ntlm          Use HTTP NTLM authentication (H)-o, --output FILE   Write output to <file> instead of stdout--pass PASS     Pass phrase for the private key (SSL/SSH)--post301       Do not switch to GET after following a 301 redirect (H)--post302       Do not switch to GET after following a 302 redirect (H)--post303       Do not switch to GET after following a 303 redirect (H)-#, --progress-bar  Display transfer progress as a progress bar--proto PROTOCOLS  Enable/disable specified protocols--proto-redir PROTOCOLS  Enable/disable specified protocols on redirect-x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port--proxy-anyauth Pick "any" proxy authentication method (H)--proxy-basic   Use Basic authentication on the proxy (H)--proxy-digest  Use Digest authentication on the proxy (H)--proxy-negotiate Use Negotiate authentication on the proxy (H)--proxy-ntlm    Use NTLM authentication on the proxy (H)-U, --proxy-user USER[:PASSWORD]  Proxy user and password--proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port-p, --proxytunnel   Operate through a HTTP proxy tunnel (using CONNECT)--pubkey KEY    Public key file name (SSH)-Q, --quote CMD     Send command(s) to server before transfer (F/SFTP)--random-file FILE  File for reading random data from (SSL)-r, --range RANGE   Retrieve only the bytes within a range--raw           Do HTTP "raw", without any transfer decoding (H)-e, --referer       Referer URL (H)-J, --remote-header-name Use the header-provided filename (H)-O, --remote-name   Write output to a file named as the remote file--remote-name-all Use the remote file name for all URLs-R, --remote-time   Set the remote file's time on the local output-X, --request COMMAND  Specify request command to use--resolve HOST:PORT:ADDRESS  Force resolve of HOST:PORT to ADDRESS--retry NUM   Retry request NUM times if transient problems occur--retry-delay SECONDS When retrying, wait this many seconds between each--retry-max-time SECONDS  Retry only within this period-S, --show-error    Show error. With -s, make curl show errors when they occur-s, --silent        Silent mode. Don't output anything--socks4 HOST[:PORT]  SOCKS4 proxy on given host + port--socks4a HOST[:PORT]  SOCKS4a proxy on given host + port--socks5 HOST[:PORT]  SOCKS5 proxy on given host + port--socks5-basic  Enable username/password auth for SOCKS5 proxies--socks5-gssapi Enable GSS-API auth for SOCKS5 proxies--socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy--socks5-gssapi-service NAME  SOCKS5 proxy service name for gssapi--socks5-gssapi-nec  Compatibility with NEC SOCKS5 server-Y, --speed-limit RATE  Stop transfers below speed-limit for 'speed-time' secs-y, --speed-time SECONDS  Time for trig speed-limit abort. Defaults to 30--ssl           Try SSL/TLS (FTP, IMAP, POP3, SMTP)--ssl-reqd      Require SSL/TLS (FTP, IMAP, POP3, SMTP)-2, --sslv2         Use SSLv2 (SSL)-3, --sslv3         Use SSLv3 (SSL)--ssl-allow-beast Allow security flaw to improve interop (SSL)--stderr FILE   Where to redirect stderr. - means stdout--tcp-nodelay   Use the TCP_NODELAY option-t, --telnet-option OPT=VAL  Set telnet option--tftp-blksize VALUE  Set TFTP BLKSIZE option (must be >512)-z, --time-cond TIME  Transfer based on a time condition-1, --tlsv1         Use => TLSv1 (SSL)--tlsv1.0       Use TLSv1.0 (SSL)--tlsv1.1       Use TLSv1.1 (SSL)--tlsv1.2       Use TLSv1.2 (SSL)--tlsv1.3       Use TLSv1.3 (SSL)--tls-max VERSION  Use TLS up to VERSION (SSL)--trace FILE    Write a debug trace to the given file--trace-ascii FILE  Like --trace but without the hex output--trace-time    Add time stamps to trace/verbose output--tr-encoding   Request compressed transfer encoding (H)-T, --upload-file FILE  Transfer FILE to destination--url URL       URL to work with-B, --use-ascii     Use ASCII/text transfer-u, --user USER[:PASSWORD]  Server user and password--tlsuser USER  TLS username--tlspassword STRING TLS password--tlsauthtype STRING  TLS authentication type (default SRP)--unix-socket FILE    Connect through this UNIX domain socket-A, --user-agent STRING  User-Agent to send to server (H)-v, --verbose       Make the operation more talkative-V, --version       Show version number and quit-w, --write-out FORMAT  What to output after completion--xattr        Store metadata in extended file attributes-q                 If used as the first parameter disables .curlrc

二、具体使用

1.当前目录新建文件

touch curl-format.txt
  • curl-format.txt内容如下
time_namelookup:  %{time_namelookup}s\ntime_connect:  %{time_connect}s\ntime_appconnect:  %{time_appconnect}s\ntime_pretransfer:  %{time_pretransfer}s\ntime_redirect:  %{time_redirect}s\ntime_starttransfer:  %{time_starttransfer}s\nspeed_download:  %{speed_download}byte/s\n----------\ntime_total:  %{time_total}s\n

2.执行命令

  • 代码如下:
curl -w "@curl-format.txt" -o /dev/null -s -X POST -H 'Content-Type:application/json' -H 'Authorization:Bearer uiopkla8cfe6sdda6725'  -d '{"os":"ios","id":"123"}' 'https://www.sample.com/code/status'
  • 以上代码就是执行一次HTTP POST请求,将请求结果输出到/dev/null,打印出网络个阶段的响应时间。
  • 参数解释
    -w “@curl-format.txt” 通知cURL使用格式化的输出文件
    -o /dev/null 将请求的输出重定向到/dev/null
    -s 通知curl不显示进度条

3.结果

time_namelookup:  0.124stime_connect:  0.167stime_appconnect:  0.323stime_pretransfer:  0.323stime_redirect:  0.000stime_starttransfer:  0.367sspeed_download:50.000byte/s----------time_total:  0.367s
  • 结果说明

    • time_namelookup:DNS 域名解析的时候,就是把域名转换成ip地址的过程
    • time_connect:TCP 连接建立的时间,就是三次握手的时间
    • time_appconnect:SSL/SSH等上层协议建立连接的时间,比如 connect/handshake 的时间
    • time_pretransfer:从请求开始到响应开始传输的时间
    • time_starttransfer:从请求开始到第一个字节将要传输的时间
    • time_total:这次请求花费的全部时间
    • speed_download:网络下载速度 单位 byte/s
  • 结果计算
    • DNS 查询:124ms
    • TCP 连接时间:pretransfter(323) - namelookup(124) = 199ms
    • 服务器处理时间:starttransfter(367) - pretransfer(323) = 44ms
    • 内容传输时间:total(367) - starttransfer(367) = 0ms

总结

本文主要是记录使用curl 获取接口请求的响应时间,包括DNS 域名解析时间,建立连接时间和全部时间等。采用–connect-timeout 1 -m 5 的两个参数的时间单位是秒,不能设置成小数,所以应用场景有限,不及上面的方法。

curl 输出接口请求响应时间相关推荐

  1. php 循环curl,PHP实现的curl批量请求操作示例

    本文实例讲述了PHP实现的curl批量请求操作.分享给大家供大家参考,具体如下: $ch = array(); $res = array(); $conn = array(); $urls = arr ...

  2. php curl 批量,PHP实现的curl批量请求操作

    这篇文章主要介绍了PHP实现的curl批量请求操作,结合实例形式分析了php使用curl进行批量请求处理的具体批量创建curl句柄.批量执行句柄.防卡死等相关操作技巧,需要的朋友可以参考下 本文实例讲 ...

  3. curl 请求日志_HTTP入门(一):在Bash中curl查看请求与响应

    HTTP入门(一):在Bash中curl查看请求与响应 本文简单总结HTTP的请求与响应. 本文主要目的是对学习内容进行总结以及方便日后查阅. 详细教程和原理可以参考HTTP文档(MDN). 本文版权 ...

  4. php请求接口两次,php curl post请求执行一次curl_exce 请求的接口确执行两次

    1.php curl post请求接口,打印日志执行了一次curl_exce,但是请求的接口却重复执行两次. 2.代码: $ch = curl_init(); if(false === $ch){ w ...

  5. java curl get_如何从Java中的curl get请求获取文件?

    我正在尝试使用API​​下载一些XBRL文件.为了做到这一点,我需要做一个卷曲的请求,就像这样:如何从Java中的curl get请求获取文件? curl -XGET http://distribut ...

  6. 使用PHP中的curl发送请求

    使用CURL发送请求的基本流程 使用CURL的PHP扩展完成一个HTTP请求的发送一般有以下几个步骤: 初始化连接句柄: 设置CURL选项: 执行并获取结果: 释放VURL连接句柄. 下面的程序片段是 ...

  7. cURL – PUT请求示例

    使用cURL -X PUT发送PUT(更新)请求以更新用户名和电子邮件的示例. Terminal $ curl -X PUT -d 'name=mkyong&email=abc@gmail.c ...

  8. java curl 使用方法_如何在Java中使用这个cURL POST请求?(Spotify API)

    我需要帮助在Java中发出cURL POST请求(到spotifyapi).我把我的解决办法解释得太离谱了 this article . 基于此,我尝试了以下方法: String command = ...

  9. php curl发送post请求失败,PHP中的使用curl发送请求(GET请求和POST请求)

    使用CURL发送请求的基本流程 使用CURL的PHP扩展完成一个HTTP请求的发送一般有以下几个步骤: 1.初始化连接句柄: 2.设置CURL选项: 3.执行并获取结果: 4.释放VURL连接句柄. ...

最新文章

  1. Type_C工作原理
  2. .Net高级技术——对象序列化
  3. 【学习笔记】JAVA基础——异常处理部分
  4. java 写文件时,输入换行字符.
  5. 2021高考技能考试成绩查询,2021年临床技能考试成绩出来了!附查询方式
  6. HBase流量限制和表负载均衡剖析
  7. ASP.NET MVC 4 中Jquery上传插件Uploadify简单使用-版本:3.2.1
  8. ibm wodm studio 开发
  9. Sketch for Mac汉化破解教程含汉化包
  10. FDB表-ARP表-路由表
  11. android 4.x tablet,Android SmartPhone应用程序对Android Tablet的支持
  12. 白话空间统计之四:P值和Z值(中)
  13. 流媒体后视镜方案关键技术--电子防眩目
  14. Fragment被replace时重复加载数据的问题
  15. 服务器系统 固态硬盘速度慢,SSD速度慢的原因和解决办法 电脑装了固态硬盘还慢怎么办...
  16. 韦东山学习笔记——UART(串口)的使用
  17. android 银联支付必须要nfc吗,手机没有NFC功能,可以使用银联云闪付功能吗?
  18. 复习单片机:温度检测 DS18B20(内含:1 DS18B20 介绍+2 硬件设计+3 软件设计+4 实验现象)
  19. Vue-vue-cli的安装
  20. wxpython问卷调查界面_7步教你搭建智能问卷调查系统

热门文章

  1. Java---多线程入门
  2. HJ68 成绩排序 ●●
  3. vue移动端h5中a标签下载/预览文件
  4. 四、s3c2440 裸机开发 通用异步收发器UARN
  5. 2020年网络搭建与应用国赛题-防火墙ipsec建立分解
  6. 查看英伟达Nvidia显卡、cuda版本
  7. [Shiro教程] Shiro 教程基于SSM(SpringMVC + Spring + Mybatis)EHCache版本
  8. java spel_Java spring SPEL表达式注入
  9. JUC Striped64
  10. java实现pdf转为word