前言
postman 可以生成各种语言的代码发送接口请求,对于会使用 postman 但python脚本还不熟练的小伙伴会很有帮助。
经常有小伙伴说:为什么我 postman 可以请求成功,用 python 无法请求成功?
code
postman 上接口调试没问题后,可以点右侧 code 按钮
可以生成 HTTP 协议的请求报文, 这对排查问题非常方便
POST /api/v1/register HTTP/1.1
Host: localhost:8000
Content-Type: application/json
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 8586703c-68a8-445b-b532-4a1b9db14eb9,ebaee06d-9612-492a-98d5-c0333bb7ca9e
Host: 49.235.92.12:7005
accept-encoding: gzip, deflate
content-length: 68
Connection: keep-alive
cache-control: no-cache
{
"username": "test_1620546381",
"password": "123456"
}
生成 python 代码段
可以选择不同的开发语言
选python requests请求
点 Copy to Clipboard 按钮会全部复制出来
import requests
url = "http://localhost:8000/api/v1/register"
payload = "{\n \"username\": \"test_1620546518\",\n \"password\": \"123456\"\n}"
headers = {
'Content-Type': "application/json",
'User-Agent': "PostmanRuntime/7.13.0",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Postman-Token': "8586703c-68a8-445b-b532-4a1b9db14eb9,155883b8-aea7-4b42-82db-d9e18b28cbce",
'Host': "49.235.92.12:7005",
'accept-encoding': "gzip, deflate",
'content-length': "68",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
curl 请求
也可以生成 curl 请求
curl -X POST \
http://localhost:8000/api/v1/register \
-H 'Accept: */*' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Type: application/json' \
-H 'Host: 49.235.92.12:7005' \
-H 'Postman-Token: 8586703c-68a8-445b-b532-4a1b9db14eb9,c96e777c-37f6-4e71-99c0-8dfa78ba516a' \
-H 'User-Agent: PostmanRuntime/7.13.0' \
-H 'accept-encoding: gzip, deflate' \
-H 'cache-control: no-cache' \
-H 'content-length: 68' \
-d '{
"username": "test_1620546615",
"password": "123456"
}'
postman 支持的语言和框架
Language | Framework |
---|---|
C | LibCurl |
C# | RestSharp |
cURL | cURL |
Dart | Dart |
Go | http package |
HTTP | (Raw HTTP request) |
Java | OkHttp |
Java | Unirest |
JavaScript | Fetch |
JavaScript | jQuery |
JavaScript | XHR |
NodeJS | Axios |
NodeJS | Native |
NodeJS | Request |
NodeJS | Unirest |
Objective-C | NSURLSession |
OCaml | Cohttp |
PHP | cURL |
PHP | Http_Request2 |
PHP | pecl_http |
PowerShell | RestMethod |
Python | http.client (Python 3) |
Python | Requests |
Ruby | NET::Http |
Shell | Httpie |
Shell | wget |
Swift | URLSession |
作者-上海悠悠 blog地址 https://www.cnblogs.com/yoyoketang/