接口测试协议分析和代理抓包

 

接口测试必要性

 

接口测试不能做什么

❖ 接⼜测试不能解决移动端的质量
❖ 仍然需要⽤户端的测试
 

七层网络模型与常见协议

 

 

网络监听:Tcpdump + Wireshark分析TCP协议

Wireshark

下载安装:https://www.wireshark.org/download.html

 

Tcpdump

Linux和mac系统自带

  • tcpdump是什么?
    用简单的话来定义tcpdump,就是:dump the traffic on a network,根据使用者的定义对网络上的数据包进行截获的包分析工具。 tcpdump可以将网络中传送的数据包的“头”完全截获下来提供分析。它支持针对网络层、协议、主机、网络或端口的过滤,并提供and、or、not等逻辑语句来帮助你去掉无用的信息。
    https://www.cnblogs.com/ggjucheng/archive/2012/01/14/2322659.html
  • 开启tcpdump 网络监听
    sudo tcpdump -Al host www.baidu.com 5 -v -w /tmp/baidu1.txt
    -v显示日志,
    -w 表示将监听的内容保存到本地,保存tmp目录下baidu1.txt文件
    host 要监听的主机
    port 要监听的端口
    Al A:以ascii的方式显示数据包,抓取web数据时很有用;l:使用标准格式进行输出
  • 使用curl命令发送请求
    curl http://www.baidu.com
  • 使用wireshark打开baidu1.txt文件
    ps:windows系统需要下载windump: https://www.winpcap.org/windump/

curl命令

curl用法指南 https://www.ruanyifeng.com/blog/2019/09/curl-reference.html

  • chrome中的copy as curl
  • 通过参数指定wd的编码
    curl -G url https://www.baidu.com --data-urlencode "wd:霍格沃兹测试学院"
     

curl --help

curl常用参数

-G 将参数携带在url里边
--data -urlcode 将参数进行编码
-s 静默输出
-o 将输出内容保存到本地
-v 打印详细发送的日志

 
 

-d 发送post请求时,携带的数据体
-I 打印头信息

-X 设置代理

curl命令使用文档

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)
     --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

 

阮一峰curl网站开发指南

http://www.ruanyifeng.com/blog/2011/09/curl.html

http://www.ruanyifeng.com/blog/2019/09/curl-reference.html

 

客户端模拟请求⼯具

  • nc
nc www.baidu.com 80 -v
GET / HTTP/1.0
Host: www.baidu.com

nc需要安装命令

  • telnet(windows系统使用)
telnet www.baidu.com 80
GET / HTTP/1.0
Host: www.baidu.com
  • curl 最常使⽤的http请求⼯具
  • postman 综合性的http协议测试⼯具

get和post

搭建demo server环境,使用以下代码

from flask import Flask, session, request, Request, make_response

app = Flask(__name__)
request: Request
app.secret_key = "key"

app.route("/request", methods=['POST', 'GET'])
def hello():
    query = request.args
    post = request.form
    return f"query: {query}\n" \
           f"post: {post}"

@app.route("/session")
def session_handle():
    for k, v in request.args.items():
        session[k] = v
    resp = make_response({k: v for k, v in session.items()})
    for k, v in request.args.items():
        resp.set_cookie(f"cookie_{k}", v)
    return resp

启动服务

set FLASK_APP=D:\Test\python\hogwarts_TD\demo\flaskdemo.py
flask run
 
 

浏览器访问 http://127.0.0.1:5000/request

 

发送get与post请求

curl -s ‘http://127.0.0.1:5000/request?a=1&b=2 4’ -v &>/tmp/get

curl -s ‘http://127.0.0.1:5000/request?a=1&b=2 4’ -d “a=3&b=4” -v &>/tmp/post

diff对比

get与post的区别总结

❖ http的method字段不同
❖ post可以附加body,可以⽀持form、json、xml、binary等各种数据格式
❖ ⾏业通⽤的规范
❖ ⽆状态变化的建议使⽤get请求
❖ 数据的写⼊与状态修改建议⽤post

cookie、seesion和token

cookie与session的区别

普通get请求与设置session的get请求diff

❖ cookie:浏览器接受服务器的Set-Cookie指令,并把cookie保存到电脑上,每
个⽹站保存的cookie只作⽤于⾃⼰的⽹站
❖ session:数据存储到服务端,只把关联数据的⼀个加密串放到cookie中标记

token应⽤场景

❖ 凭借认证信息获取token,或者通过后台配置好token
企业微信,获取token的api

 

 

在github上创建token

❖ 在相关请求中使⽤token,多数是以query参数的形态提供
企业微信获取token后,使用token
https://qyapi.weixin.qq.com/cgi-bin/user/create?
access_token=ACCESS_TOKEN
❖ https://qyapi.weixin.qq.com/cgi-bin/department/create?
access_token=ACCESS_TOKEN

session与token的区别

❖ token是⼀个⽤户请求时附带的请求字段,⽤于验证⾝份与权限
❖ session可以基于cookie,也可以基于query参数,⽤于关联⽤户相关数据
❖ 跨端应⽤的时候,⽐如android原⽣系统不⽀持cookie
❖ 需要⽤token识别⽤户
❖ 需要⽤把sessionid保存到http请求中的header或者query字段中

URL 链接中 井号#、问号?、连接符& 分别有什么作用?

https://blog.csdn.net/weixin_43582101/article/details/90695881?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1
一、井号
井号#:表示网页中的一个位置,被称之为锚点,常用于某个网页间不同位置的跳转,简单的说就是在一个网页中,URL 不变的情况下,通过添加“#buy”的字符在 URL 最后可以跳转到当前网页中已经定义好的锚点(id=“buy”)位置;
同样#的改变也会增加浏览器的历史记录,也就是说我们可以通过“后退”按钮回到上一个位置,而熟悉网页开发的朋友们可能也会用于 ajax 的一些操作中,以此来实现不同的访问状态和改变页面访问内容,从而也可以实现那种无刷新载入的效果。

例如:https://zhan.leiue.com/fanly-mip.html#buy (访问该链接就可以直接跳转到 Fanly MIP 主题页面的购买位置哦)

二、问号
问号?:常用于动态网站,实现不同的参数值而生成不同的页面或者返回不同的结果,
例如 WordPress 的动态链接就是/?p=ID,其中的 p 就表示 post 文章,ID 就表示文章的 ID,从而可以通过文章的 ID 来访问不同的文章。
当然我们还常用的就是通过问号+任意参数来实现页面的刷新,从而获得最新的页面或者缓存的刷新

例如:https://i.leiue.com/avatar/?size=100 (访问该链接就可以获得泪雪用户中心默认的用户头像,并且其 size 就是图像像素大小,所以就会是一个 100px 的头像显示)

三、连接
连接符&:既然被叫做是链接符号,那就是连接的作用,也可以说是不同参数的间隔符,一般与问号结合使用,一个动态 URL 链接中以问号开始第一个参数,同&连接符来串联多个参数和值。

例如:https://i.leiue.com/avatar/?size=100&time=20171120 (还是以泪雪个人中心的头像举例,因为头像是有缓存功能的,如果用户修改了头像后,访问原来的地址可能就会存在头像未修改的情况,那么我们在保证要获得 100px 大小的头像并且要刷新缓存就可以使用连接符&多添加一个任意的参数,以此来获取最新的头像)

代理工具Charles

Map Remote

 
 

Map Local

 
 
 
 

Rewrite

 

修改雪球列表页股票的列表内容,修改为上千只股票

raw=$(cat /tmp/stock.json)
raw=$(echo $raw |jq '.data.items+=.data.items'| jq '.data.items_size+=.data.items_size' )

raw=$(cat /d/Test/hogwarts/接口测试/stock.json)

https://stedolan.github.io/jq/#

 
 
 
posted @ 2020-05-23 08:42  捷后愚生  阅读(427)  评论(0编辑  收藏  举报