测试游记

HTTP 接口测试基础 · 第 03 篇|用 HTTPie 在命令行调试接口

来呀~

欢迎关注我的公众号「测试游记」

官方网站:https://httpie.org/

常用的http请求工具的缺点

  • postman

不够灵活

需要打开客户端「打开慢」

学习成本高「测试,断言等」

  • Jmeter

臃肿

麻烦

学习成本高「变量,cookie的管理等」

  • curl

参数多

不够灵活

主要在Linux平台中使用

学习成本高

  • wget

Linux中下载资源的工具

参数多

主要功能是命令行下载,功能单一

HTTP客户端命令行工具-HTTPie

  • 基于命令行

  • 支持JSON

  • 支持语法高亮,格式化输出

  • 支持类似 wget 的下载模式

  • 支持session会话

  • 支持HTTPS

  • 支持代理,认证

  • 支持表单提交,文件提交

  • 支持查看请求头、请求体、响应头或响应体

  • 支持多平台

安装

windows:

  1. $ pip install --upgrade pip setuptools

  2. $ pip install --upgrade httpie

其他:https://httpie.org/doc#installation

查看帮助

官方文档:https://httpie.org/doc

  1. $ http --help

  2. zhongxindeMacBook-Pro:~ zhongxin$ http --help

  3. usage: http [--json] [--form] [--pretty {all,colors,format,none}]

  4. [--style STYLE] [--print WHAT] [--headers] [--body] [--verbose]

  5. [--all] [--history-print WHAT] [--stream] [--output FILE]

  6. [--download] [--continue]

  7. [--session SESSION_NAME_OR_PATH | --session-read-only SESSION_NAME_OR_PATH]

  8. [--auth USER[:PASS]] [--auth-type {basic,digest}]

  9. [--proxy PROTOCOL:PROXY_URL] [--follow]

  10. [--max-redirects MAX_REDIRECTS] [--timeout SECONDS]

  11. [--check-status] [--verify VERIFY]

  12. [--ssl {ssl2.3,tls1,tls1.1,tls1.2}] [--cert CERT]

  13. [--cert-key CERT_KEY] [--ignore-stdin] [--help] [--version]

  14. [--traceback] [--default-scheme DEFAULT_SCHEME] [--debug]

  15. [METHOD] URL [REQUEST_ITEM [REQUEST_ITEM ...]]

  16. HTTPie - a CLI, cURL-like tool for humans. <http://httpie.org>

  17. Positional Arguments:

  18. These arguments come after any flags and in the order they are listed here.

  19. Only URL is required.

  20. METHOD

  21. The HTTP method to be used for the request (GET, POST, PUT, DELETE, ...).

  22. This argument can be omitted in which case HTTPie will use POST if there

  23. is some data to be sent, otherwise GET:

  24. $ http example.org # => GET

  25. $ http example.org hello=world # => POST

  26. URL

  27. The scheme defaults to 'http://' if the URL does not include one.

  28. (You can override this with: --default-scheme=https)

  29. You can also use a shorthand for localhost

  30. $ http :3000 # => http://localhost:3000

  31. $ http :/foo # => http://localhost/foo

  32. REQUEST_ITEM

  33. Optional key-value pairs to be included in the request. The separator used

  34. determines the type:

  35. ':' HTTP headers:

  36. Referer:http://httpie.org Cookie:foo=bar User-Agent:bacon/1.0

  37. '==' URL parameters to be appended to the request URI:

  38. search==httpie

  39. '=' Data fields to be serialized into a JSON object (with --json, -j)

  40. or form data (with --form, -f):

  41. name=HTTPie language=Python description='CLI HTTP client'

  42. ':=' Non-string JSON data fields (only with --json, -j):

  43. awesome:=true amount:=42 colors:='["red", "green", "blue"]'

  44. '@' Form file fields (only with --form, -f):

  45. cs@~/Documents/CV.pdf

  46. '=@' A data field like '=', but takes a file path and embeds its content:

  47. essay=@Documents/essay.txt

  48. ':=@' A raw JSON field like ':=', but takes a file path and embeds its content:

  49. package:=@./package.json

  50. You can use a backslash to escape a colliding separator in the field name:

  51. field-name-with\:colon=value

  52. Predefined Content Types:

  53. --json, -j

  54. (default) Data items from the command line are serialized as a JSON object.

  55. The Content-Type and Accept headers are set to application/json

  56. (if not specified).

  57. --form, -f

  58. Data items from the command line are serialized as form fields.

  59. The Content-Type is set to application/x-www-form-urlencoded (if not

  60. specified). The presence of any file fields results in a

  61. multipart/form-data request.

  62. Output Processing:

  63. --pretty {all,colors,format,none}

  64. Controls output processing. The value can be "none" to not prettify

  65. the output (default for redirected output), "all" to apply both colors

  66. and formatting (default for terminal output), "colors", or "format".

  67. --style STYLE, -s STYLE

  68. Output coloring style (default is "auto"). One of:

  69. abap, algol, algol_nu, arduino, auto, autumn, borland, bw,

  70. colorful, default, emacs, friendly, fruity, igor, lovelace,

  71. manni, monokai, murphy, native, paraiso-dark, paraiso-light,

  72. pastie, perldoc, rainbow_dash, rrt, sas, solarized,

  73. solarized-dark, solarized-light, stata, stata-dark, stata-

  74. light, tango, trac, vim, vs, xcode

  75. The "auto" style follows your terminal's ANSI color styles.

  76. For non-auto styles to work properly, please make sure that the

  77. $TERM environment variable is set to "xterm-256color" or similar

  78. (e.g., via `export TERM=xterm-256color' in your ~/.bashrc).

  79. Output Options:

  80. --print WHAT, -p WHAT

  81. String specifying what the output should contain:

  82. 'H' request headers

  83. 'B' request body

  84. 'h' response headers

  85. 'b' response body

  86. The default behaviour is 'hb' (i.e., the response headers and body

  87. is printed), if standard output is not redirected. If the output is piped

  88. to another program or to a file, then only the response body is printed

  89. by default.

  90. --headers, -h

  91. Print only the response headers. Shortcut for --print=h.

  92. --body, -b

  93. Print only the response body. Shortcut for --print=b.

  94. --verbose, -v

  95. Verbose output. Print the whole request as well as the response. Also print

  96. any intermediary requests/responses (such as redirects).

  97. It's a shortcut for: --all --print=BHhb

  98. --all

  99. By default, only the final request/response is shown. Use this flag to show

  100. any intermediary requests/responses as well. Intermediary requests include

  101. followed redirects (with --follow), the first unauthorized request when

  102. Digest auth is used (--auth=digest), etc.

  103. --history-print WHAT, -P WHAT

  104. The same as --print, -p but applies only to intermediary requests/responses

  105. (such as redirects) when their inclusion is enabled with --all. If this

  106. options is not specified, then they are formatted the same way as the final

  107. response.

  108. --stream, -S

  109. Always stream the output by line, i.e., behave like `tail -f'.

  110. Without --stream and with --pretty (either set or implied),

  111. HTTPie fetches the whole response before it outputs the processed data.

  112. Set this option when you want to continuously display a prettified

  113. long-lived response, such as one from the Twitter streaming API.

  114. It is useful also without --pretty: It ensures that the output is flushed

  115. more often and in smaller chunks.

  116. --output FILE, -o FILE

  117. Save output to FILE instead of stdout. If --download is also set, then only

  118. the response body is saved to FILE. Other parts of the HTTP exchange are

  119. printed to stderr.

  120. --download, -d

  121. Do not print the response body to stdout. Rather, download it and store it

  122. in a file. The filename is guessed unless specified with --output

  123. [filename]. This action is similar to the default behaviour of wget.

  124. --continue, -c

  125. Resume an interrupted download. Note that the --output option needs to be

  126. specified as well.

  127. Sessions:

  128. --session SESSION_NAME_OR_PATH

  129. Create, or reuse and update a session. Within a session, custom headers,

  130. auth credential, as well as any cookies sent by the server persist between

  131. requests.

  132. Session files are stored in:

  133. /Users/zhongxin/.httpie/sessions/<HOST>/<SESSION_NAME>.json.

  134. --session-read-only SESSION_NAME_OR_PATH

  135. Create or read a session without updating it form the request/response

  136. exchange.

  137. Authentication:

  138. --auth USER[:PASS], -a USER[:PASS]

  139. If only the username is provided (-a username), HTTPie will prompt

  140. for the password.

  141. --auth-type {basic,digest}, -A {basic,digest}

  142. The authentication mechanism to be used. Defaults to "basic".

  143. "basic": Basic HTTP auth

  144. "digest": Digest HTTP auth

  145. Network:

  146. --proxy PROTOCOL:PROXY_URL

  147. String mapping protocol to the URL of the proxy

  148. (e.g. http:http://foo.bar:3128). You can specify multiple proxies with

  149. different protocols.

  150. --follow, -F

  151. Follow 30x Location redirects.

  152. --max-redirects MAX_REDIRECTS

  153. By default, requests have a limit of 30 redirects (works with --follow).

  154. --timeout SECONDS

  155. The connection timeout of the request in seconds. The default value is

  156. 30 seconds.

  157. --check-status

  158. By default, HTTPie exits with 0 when no network or other fatal errors

  159. occur. This flag instructs HTTPie to also check the HTTP status code and

  160. exit with an error if the status indicates one.

  161. When the server replies with a 4xx (Client Error) or 5xx (Server Error)

  162. status code, HTTPie exits with 4 or 5 respectively. If the response is a

  163. 3xx (Redirect) and --follow hasn't been set, then the exit status is 3.

  164. Also an error message is written to stderr if stdout is redirected.

  165. SSL:

  166. --verify VERIFY

  167. Set to "no" (or "false") to skip checking the host's SSL certificate.

  168. Defaults to "yes" ("true"). You can also pass the path to a CA_BUNDLE file

  169. for private certs. (Or you can set the REQUESTS_CA_BUNDLE environment

  170. variable instead.)

  171. --ssl {ssl2.3,tls1,tls1.1,tls1.2}

  172. The desired protocol version to use. This will default to

  173. SSL v2.3 which will negotiate the highest protocol that both

  174. the server and your installation of OpenSSL support. Available protocols

  175. may vary depending on OpenSSL installation (only the supported ones

  176. are shown here).

  177. --cert CERT

  178. You can specify a local cert to use as client side SSL certificate.

  179. This file may either contain both private key and certificate or you may

  180. specify --cert-key separately.

  181. --cert-key CERT_KEY

  182. The private key to use with SSL. Only needed if --cert is given and the

  183. certificate file does not contain the private key.

  184. Troubleshooting:

  185. --ignore-stdin, -I

  186. Do not attempt to read stdin.

  187. --help

  188. Show this help message and exit.

  189. --version

  190. Show version and exit.

  191. --traceback

  192. Prints the exception traceback should one occur.

  193. --default-scheme DEFAULT_SCHEME

  194. The default scheme to use if not specified in the URL.

  195. --debug

  196. Prints the exception traceback should one occur, as well as other

  197. information useful for debugging HTTPie itself and for reporting bugs.

  198. For every --OPTION there is also a --no-OPTION that reverts OPTION

  199. to its default value.

  200. Suggestions and bug reports are greatly appreciated:

  201. https://github.com/jakubroztocil/httpie/issues

创建一个简单的Flask项目进行测试

  1. from flask import Flask

  2. app = Flask(__name__)

  3. @app.route('/')

  4. def hello_world():

  5. return 'Hello World!'

  6. if __name__ == '__main__':

  7. app.run()

语法格式

  1. http [flags] [METHOD] URL [ITEM [ITEM]]

get请求

  1. $ http url

  2. zhongxindeMacBook-Pro:~ zhongxin$ http http://127.0.0.1:5000/

  3. HTTP/1.0 200 OK

  4. Content-Length: 12

  5. Content-Type: text/html; charset=utf-8

  6. Date: Thu, 10 Oct 2019 15:16:27 GMT

  7. Server: Werkzeug/0.15.5 Python/3.7.1

  8. Hello World!

post请求

把测试代码改一改

  1. from flask import Flask, request

  2. app = Flask(__name__)

  3. @app.route('/', methods=['POST', 'GET'])

  4. def hello_world():

  5. if request.method == 'GET':

  6. return 'Hello World!'

  7. elif request.method == 'POST':

  8. data = request.get_data()

  9. return data

  10. if __name__ == '__main__':

  11. app.run()

  1. $ http url key=value key=value

  2. $ http POST url key=value key=value

  3. zhongxindeMacBook-Pro:~ zhongxin$ http http://127.0.0.1:5000/ name='zx' age=25

  4. HTTP/1.0 200 OK

  5. Content-Length: 27

  6. Content-Type: text/html; charset=utf-8

  7. Date: Thu, 10 Oct 2019 15:21:13 GMT

  8. Server: Werkzeug/0.15.5 Python/3.7.1

  9. {

  10. "age": "25",

  11. "name": "zx"

  12. }

delete请求

再修改一下测试代码

  1. @app.route('/', methods=['POST', 'GET','DELETE'])

  2. def hello_world():

  3. if request.method == 'GET':

  4. return 'Hello World!'

  5. elif request.method == 'POST':

  6. data = request.get_data()

  7. return data

  8. elif request.method =='DELETE':

  9. return '删啥呢'

  1. $ http DELETE http://127.0.0.1:5000/

  2. zhongxindeMacBook-Pro:~ zhongxin$ http DELETE http://127.0.0.1:5000/

  3. HTTP/1.0 200 OK

  4. Content-Length: 9

  5. Content-Type: text/html; charset=utf-8

  6. Date: Thu, 10 Oct 2019 15:24:14 GMT

  7. Server: Werkzeug/0.15.5 Python/3.7.1

  8. 删啥呢

其他请求也类似

form表单

先安装一下 flask-wtf

  1. $ pip install flask-wtf

  1. from flask import Flask, request

  2. from flask_wtf import FlaskForm

  3. from wtforms import StringField, TextAreaField

  4. app = Flask(__name__)

  5. class MyForm(FlaskForm):

  6. name = StringField('Name')

  7. age = TextAreaField('Age')

  8. @app.route('/', methods=['POST', 'GET', 'DELETE'])

  9. def hello_world():

  10. if request.method == 'GET':

  11. return 'Hello World!'

  12. elif request.method == 'POST':

  13. form = MyForm(csrf_enabled=False)

  14. name = form.name.data

  15. age = form.age.data

  16. return f'从form表单拿到的name:{name},age:{age}'

  17. elif request.method == 'DELETE':

  18. return '删啥呢'

  19. if __name__ == '__main__':

  20. app.run()

  1. $ http -f http://127.0.0.1:5000/ name=zx age=25

  2. HTTP/1.0 200 OK

  3. Content-Length: 36

  4. Content-Type: text/html; charset=utf-8

  5. Date: Thu, 10 Oct 2019 15:35:00 GMT

  6. Server: Werkzeug/0.15.5 Python/3.7.1

  7. 从form表单拿到的name:zx,age:25

使用 -v查看请求的全部信息

  1. zhongxindeMacBook-Pro:~ zhongxin$ http -f -v http://127.0.0.1:5000/ name=zx age=25

  2. POST / HTTP/1.1

  3. Accept: */*

  4. Accept-Encoding: gzip, deflate

  5. Connection: keep-alive

  6. Content-Length: 14

  7. Content-Type: application/x-www-form-urlencoded; charset=utf-8

  8. Host: 127.0.0.1:5000

  9. User-Agent: HTTPie/1.0.3

  10. name=zx&age=25

  11. HTTP/1.0 200 OK

  12. Content-Length: 36

  13. Content-Type: text/html; charset=utf-8

  14. Date: Thu, 10 Oct 2019 15:36:31 GMT

  15. Server: Werkzeug/0.15.5 Python/3.7.1

  16. 从form表单拿到的name:zx,age:25

查询字符串产生

url?xx=xx&xx=xx

使用两个 =:name==zx age==25

  1. $ http -v http://127.0.0.1:5000/ name==zx age==25

  2. zhongxindeMacBook-Pro:~ zhongxin$ http -v http://127.0.0.1:5000/ name==zx age==25

  3. GET /?name=zx&age=25 HTTP/1.1

  4. Accept: */*

  5. Accept-Encoding: gzip, deflate

  6. Connection: keep-alive

  7. Host: 127.0.0.1:5000

  8. User-Agent: HTTPie/1.0.3

  9. HTTP/1.0 200 OK

  10. Content-Length: 12

  11. Content-Type: text/html; charset=utf-8

  12. Date: Thu, 10 Oct 2019 15:39:24 GMT

  13. Server: Werkzeug/0.15.5 Python/3.7.1

  14. Hello World!

修改请求头

  1. $ http -v http://127.0.0.1:5000/ User-Agent:666

  2. GET / HTTP/1.1

  3. Accept: */*

  4. Accept-Encoding: gzip, deflate

  5. Connection: keep-alive

  6. Host: 127.0.0.1:5000

  7. User-Agent: 666

  8. HTTP/1.0 200 OK

  9. Content-Length: 12

  10. Content-Type: text/html; charset=utf-8

  11. Date: Thu, 10 Oct 2019 15:40:42 GMT

  12. Server: Werkzeug/0.15.5 Python/3.7.1

  13. Hello World!

传递JSON

  1. http -v http://127.0.0.1:5000/ z:=[1,2,3]

  2. zhongxindeMacBook-Pro:~ zhongxin$ http -v http://127.0.0.1:5000/ z:=[1,2,3]

  3. POST / HTTP/1.1

  4. Accept: application/json, */*

  5. Accept-Encoding: gzip, deflate

  6. Connection: keep-alive

  7. Content-Length: 16

  8. Content-Type: application/json

  9. Host: 127.0.0.1:5000

  10. User-Agent: HTTPie/1.0.3

  11. {

  12. "z": [

  13. 1,

  14. 2,

  15. 3

  16. ]

  17. }

  18. HTTP/1.0 200 OK

  19. Content-Length: 32

  20. Content-Type: text/html; charset=utf-8

  21. Date: Thu, 10 Oct 2019 15:46:40 GMT

  22. Server: Werkzeug/0.15.5 Python/3.7.1

  23. 从form表单拿到的name:,age:

上传文件

  1. class MyForm(FlaskForm):

  2. name = StringField('Name')

  3. age = TextAreaField('Age')

  4. photo = FileField('Photo')

  1. $ http -v -f http://127.0.0.1:5000/ age=25 name=zx photo@/Users/zhongxin/Desktop/httpie_test/小哀.png

  2. zhongxindeMacBook-Pro:~ zhongxin$ http -v -f http://127.0.0.1:5000/ age=25 name=zx photo@/Users/zhongxin/Desktop/httpie_test/小哀.png

  3. POST / HTTP/1.1

  4. Accept: */*

  5. Accept-Encoding: gzip, deflate

  6. Connection: keep-alive

  7. Content-Length: 1307355

  8. Content-Type: multipart/form-data; boundary=e9ff6d5440b8069e68bf49813d0a5ddd

  9. Host: 127.0.0.1:5000

  10. User-Agent: HTTPie/1.0.3

  11. +-----------------------------------------+

  12. | NOTE: binary data not shown in terminal |

  13. +-----------------------------------------+

  14. HTTP/1.0 200 OK

  15. Content-Length: 36

  16. Content-Type: text/html; charset=utf-8

  17. Date: Thu, 10 Oct 2019 16:09:15 GMT

  18. Server: Werkzeug/0.15.5 Python/3.7.1

  19. 从form表单拿到的name:zx,age:25

小结

两张静态记录卡分别表示给出的输入和观察到的结果
保留发出的内容和观察到的结果,才能回看这次交互是否符合预期。图中只有预先做好的虚构记录。
  • name:value 修改请求头

  • name==valueurl查询字符串参数

  • name=valueJSON或者加 -f变为form表单提交

  • name:=value传递JSON的布尔,数值,嵌套,Array类型「类似python列表」

  • name@/dir/file以form表单来上传文件

获取请求和响应信息

虚构响应上方是状态等摘要,下面是单独的内容区域
阅读响应时,状态和相关元信息与实际返回内容是两部分。状态正常,也值得继续核对内容。
  • 获取响应头: -h

  • 获取响应体: -b

  • 获取请求头: -p H 或 --print=H

  • 获取请求体: -p B 或 --print=B

认证

Flask例子懒得打了,就这样看看好了

Basic auth

  1. $ http -a username:password example.org

Digest auth

  1. $ http -A digest -a username:password example.org

Sessions

  1. # 创建新会话

  2. $ http --session=/tmp/session.json example.org API-Token:123

  3. # 使用旧的会话信息

  4. $ http --session=/tmp/session.json example.org

本文视频讲解

打开或下载 MP4 ↗

查看系列目录 ↗

评论与讨论

使用 GitHub 账号留言,评论公开显示。

搜索文章