分享

postman使用教程9-点 code 按钮生成代码段

 上海悠悠 2021-05-27

前言

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 支持的语言和框架

LanguageFramework
CLibCurl
C#RestSharp
cURLcURL
DartDart
Gohttp package
HTTP(Raw HTTP request)
JavaOkHttp
JavaUnirest
JavaScriptFetch
JavaScriptjQuery
JavaScriptXHR
NodeJSAxios
NodeJSNative
NodeJSRequest
NodeJSUnirest
Objective-CNSURLSession
OCamlCohttp
PHPcURL
PHPHttp_Request2
PHPpecl_http
PowerShellRestMethod
Pythonhttp.client (Python 3)
PythonRequests
RubyNET::Http
ShellHttpie
Shellwget
SwiftURLSession

2021年第七期《python接口自动化+测试开发》课程,4月18号开学(火热报名中!)

4月18号-7月11号,20:30-22:30

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多