接口测试-发送post数据请求(十)

1、判断请求连接内的数据格式,具体参考前一章的四种编码数据格式

 

 2、代码实现

 1 # coding:utf-8
 2 import requests
 3 # 先打开登录首页,获取部分session
 4 url = "http://localhost:8080/jenkins/j_acegi_security_check"
 5 headers = {
 6             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0"
 7            }  # get方法其它加个ser-Agent就可以了
 8 d = {"j_username": "admin",
 9      "j_password": "111111",
10      "from": "",
11      "Submit": u"登录",
12      "remember_me": "on"
13      }
14 s = requests.session()
15 r = s.post(url, headers=headers, data=d)
16 print (r.content.decode('utf-8')
)

  

3、数据转化

请求有时是dict有时是json

datas = {'key1':'value1','key2':'value2'}

json_data = json.dumps(datas,ensure_ascii=False)#字典转json
print(type(json_data))

dict_data = json.loads(datas)#json转字典
print(type(dict_data))

# 字典转换成json 存入本地文件
with open('./a.txt','w') as f:
    # 设置不转换成ascii  json字符串首缩进
    f.write( json.dumps( dict_data,ensure_ascii=False,indent=2 ) )

  

#json.load,从文件打开json数据转换成字典
with open("write_json.json", encoding="utf-8") as f:
  json_file = json.load(f)
print(json_file)

  

posted @ 2022-03-24 11:28  究极不吃香菜  阅读(76)  评论(0编辑  收藏  举报