python中requests库的post请求 4种类型参数

 用python来验证接口正确性,主要流程有4步:

1 设置url

2 设置消息头

3 设置消息体

4 获取响应

5 解析相应

6 验证数据

Content-Type的格式有四种:分别是application/x-www-form-urlencoded(这也是默认格式)、application/json、text/xml以及multipart/form-data格式。

(一)application/x-www-form-urlencoded数据格式

请看代码:

datas = {'parameter1':'12345','parameter2':'23456'}
r = requests.post('http://example.com',data=datas)
print(r.content)
print(r.status_code)

  解说:Reqeusts支持以application/x-www-form-urlencoded数据格式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。

(二)application/json数据格式 

 application/json格式的请求头是指用来告诉服务端post过去的消息主体是序列化后的 JSON 字符串。

请看带代码:

url = 'http://www.example/post'
s = json.dumps({'key1': 'value1', 'key2': 'value2'})
r = requests.post(url, data=s)
print (r.text)

区别:

这里我们可以发现Requests模拟post请求时,请求头格式为application/x-www-form-urlencoded与application/json的主要差别在于请求主体的构造格式(前者是键值对,后者是JSON串),前者直接用字典传入,后者用json.dumps()函数将字典转为JSON串即可。
(三)text/xml数据格式
请看代码:
xml = """my xml"""
headers = {'Content-Type': 'application/xml'}
requests.post('http://www.example.com', data=xml, headers=headers)
或者把xml作为一个文件来传输:
import requests

def request_ws(request):
with open(archivo_request,"r") as archivo:
    request_data = archivo.read()

target_url = "http://127.0.0.1:8000/?wsdl"

headers = {'Content-type':'text/xml'}

data_response = requests.post(target_url, data=request_data, headers=headers)

(四)multipart/form-data数据格式
除了传统的application/x-www-form-urlencoded表单,我们另一个经常用到的是上传文件用的表单,这种表单的类型为multipart/form-data,
multipart/form-data主要用于文件上传,当我们使用它时,必须让 form表单的enctype 等于 multipart/form-data
直接来看一个请求示例,主要:
请看代码(
实现上传本地的test.txt文件):

import requests
files = {"file": open("C:/Users/Administrator/Desktop/test.txt", "rb")}
r = requests.post("http://httpbin.org/post", files=files)
print(r.text)
具体请看实际例子:

import requests
import json
# 设置URL
url = "http://demo.9meikf.cn/usystem/auto/getAnswer.do"
# 设置消息头
headers = {
    "Cookie":"JSESSIONID=EA01FF2B025861F39E29712C97F7DF69;CASTGC=TGT-136-bLQMf0CAikK4BGaydOfIeKd6tWpZQEznJ2ZWdcVl9ofI4LiaQb-cas01.example.org",
    "Content-Type":"application/json"
    }
# 设置消息体
data = {"companyId":"48622",
        "nodeId":6,
        "question":"不需要",
        "templateId":"c6f5ad67fc2c11e8a11800163e086942"}
# 获取相应
response=requests.post(url,headers=headers,data=json.dumps(data))
print("Status code:",response.status_code)
print(response.text)
# 解析相应
info=response.json()
# 验证数据
assert str(info['answer'])=='reject'

posted on 2020-10-26 09:30  测试好家伙  阅读(31019)  评论(0编辑  收藏  举报

导航