做 web 开发少不了测试网络请求,虽然现在有很多方便的工具(如:postman)都能很好的
做到模拟请求,但是在没有界面的 Linux 服务器上,还是命令行比较实用,比如:
cURL ,它大而全,是我们第一个想到的工具,但想要
用 cURL 很好的完成查看网络请求各种数据的任务,需要一些深入了解,在我的文章
网络请求工具 cURL中有介绍下面我想给大家
介绍一个更加直观的网络请求测试工具 HTTPie 它能更好的支持
JSON 格式化展示,代码高亮,类 wget 下载等功能

网络请求工具 HTTPie-LMLPHP

上图就是一个最简单的 get 请求,不要担心不明白 :8002 是什么意思,下面我们会
一一介绍

安装

MacOS

1
$ brew install httpie

Ubuntu

1
2
$ sudo apt update -y
$ sudo apt install -y httpie

CentOS

1
2
$ sudo yum update -y
$ sudo yum install -y epel-release httpie

Python

1
$ pip install httpie

使用

请求状态

1
2
3
4
$ http example.org          # 默认 GET 请求
$ http POST example.org
$ http PUT example.org
$ http DELETE example.org

本地短链接

1
2
$ http :            # GET localhost ,默认80端口
$ http :8002/test # GET lcoalhost:8002/test

参数传递

URL 地址参数

1
2
$ http example.org name=='hello world' age==26
GET /?name=hello+world&age=26

JSON 数据

字符串值可以直接使用 = 来模拟 JSON 结构传递,缺省请求状态为 POST

1
2
$ http POST example.org name=wxnacy
# ==> {"name": "wxnacy"}

传递值不是字符串的话也可以用 := 方式传递

1
2
$ http example.org name=wxnacy age:=26 flag:=false tags:='["http", "url"]'
# ==> {"name": "wxnacy", "age": 26, "flag": false, "tags": ["http", "url"]}

我们还可以使用 =@ 来传递文本文件,使用 :=@ 来传递 json 文件

1
2
$ http example.org hello=@hello.txt file:=@kwargs.json
# ==> {"hello": "hello world", "file": {"name": "wxnacy"}}

还可以将 json 文件直接传值

1
$ http example.org < file.json

你也可以使用 --json-j 确保 Acceptapplication/json

Forms

提交 forms 数据和 JSON 请求很相似,只需要使用 --form, -f 参数,确保
Content-Type: application/x-www-form-urlencoded; charset=utf-8 只是传值的话,
使用 = 符号

1
$ http POST -f example.org name='helle world'

需要上传文件时使用 @ 符号,此时请求头 Content-Type 自动变为
multipart/form-data

1
$ http POST -f example.org name=wxnacy file@file.json

头信息

设置头信息非常简单,需要用 : 符号

1
$ http example.org X-API:1111                 # GET example.org

如果想给某个头信息设置空置,可以在 : 后跟空字符串

1
$ http httpbin.org/headers Accept: User-Agent:

另外官方给出如果头信息整个传空值可以使用 'Header;' ,但我实验并没有效果

下载

1
2
$ http example.org > file                    #
$ http --download example.org/file # 类 wget 下载

https

1
$ alias https='http --default-scheme=https'
03-16 14:08