如果你是一名PHP程序員,那么你一定用過(guò)cURL。cURL是一個(gè)強(qiáng)大的HTTP客戶端,但使用起來(lái)過(guò)于繁瑣。最近,我發(fā)現(xiàn)了一個(gè)更加友好的工具:HTTPie。
HTTPie是一個(gè)命令行工具,用于發(fā)送HTTP請(qǐng)求并顯示結(jié)果。與cURL相比,HTTPie的優(yōu)勢(shì)在于它更加易于使用,并且輸出結(jié)果更加美觀。下面是一個(gè)簡(jiǎn)單的例子:
http GET https://api.github.com/users/octocat
這個(gè)例子演示了如何使用HTTPie發(fā)送一個(gè)GET請(qǐng)求,訪問(wèn)Github上octocat用戶的信息。HTTPie會(huì)自動(dòng)將響應(yīng)轉(zhuǎn)換成JSON,并以彩色輸出的形式顯示在終端中:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Encoding: gzip
Content-Type: application/json; charset=utf-8
ETag: "5e39e2b335d9345a323bc0aea23dbcdb"
Server: GitHub.com
Status: 200 OK
X-GitHub-Media-Type: github.v3
X-GitHub-Request-Id: 61A7:814B:113A86:1924EC:5E2EDE97
{
"bio": null,
"blog": "http://www.github.com/blog",
"company": null,
"created_at": "2011-01-25T18:44:36Z",
"email": null,
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"followers": 5245,
"followers_url": "https://api.github.com/users/octocat/followers",
"following": 0,
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"gravatar_id": "",
"hireable": null,
"html_url": "https://github.com/octocat",
"id": 583231,
"location": "San Francisco",
"login": "octocat",
"name": "The Octocat",
"node_id": "MDQ6VXNlcjU4MzIzMQ==",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"public_gists": 411,
"public_repos": 107,
"received_events_url": "https://api.github.com/users/octocat/received_events",
"repos_url": "https://api.github.com/users/octocat/repos",
"site_admin": false,
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"type": "User",
"updated_at": "2020-01-28T16:35:13Z",
"url": "https://api.github.com/users/octocat"
}
可以看到,HTTPie的輸出非常易于理解,它將響應(yīng)頭和響應(yīng)體分開(kāi)顯示,讓我們可以更加方便地查看響應(yīng)內(nèi)容。
除了GET請(qǐng)求,HTTPie還支持其他常見(jiàn)的HTTP請(qǐng)求方法,例如POST、PUT和DELETE。下面是一個(gè)例子,演示了如何使用HTTPie發(fā)送一個(gè)POST請(qǐng)求,提交JSON格式的數(shù)據(jù):
http POST "https://httpbin.org/post" name=John age:=25
該請(qǐng)求將發(fā)送一條包含name和age參數(shù)的POST請(qǐng)求,并將數(shù)據(jù)作為JSON格式提交到httpbin.org上。響應(yīng)的內(nèi)容如下:
{
"args": {},
"data": "{\"name\": \"John\", \"age\": 25}\n",
"files": {},
"form": {},
"headers": {
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "30",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "HTTPie/0.9.8"
},
"json": {
"age": 25,
"name": "John"
},
"origin": "115.236.41.74",
"url": "https://httpbin.org/post"
}
HTTPie將請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)都展示了出來(lái),讓用戶可以更加方便地檢查請(qǐng)求和響應(yīng)數(shù)據(jù)的正確性。
最后,我想提醒一點(diǎn),HTTPie不是萬(wàn)能的,它與cURL相比在某些功能上可能存在一些限制。因此,在使用HTTPie時(shí),我們要注意不同場(chǎng)景下所需的功能,選擇合適的工具。