in _encode
raise UnicodeEncodeError(
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 9-10: Body ('XXX') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8. 关于此python错误的解决方案
翻译:不能解析Body里的字符,就是编码格式不对!
使用场景:用python做接口测试,request的封装,我的所有数据是通过excel里读取传过来的,在这里只是做个封装
分析及解决方法:在使用时由于传入的post请求里 ,data参数值有中文引起的,那么我们就需要对传入的data数据设置编码!!
如下面代码:
import requests
import unittest
class HttpRequest:
'''利用requests封装get/post/put请求'''
# **将传参参数化,在调用函数时候传参更灵活,如不传参可以直接将参数放在函数里
def http_request(self,url,data,method):
# 抓包获取的头部
data=data.encode('utf-8')#解决问题的方法!!!防止data传参的中文乱码!或在post下面专门设置
header= {
"authoriz": "yjttGoo7dX0" #token
,"Content-Type":"application/json;charset=utf-8"
}
if method=='get':
#verify = False是不验证ssl
# res = requests.get(url, data, cookies=cookie, verify=False) # 返回一个消息实体,
res = requests.get(url, data,headers=header,verify=False) # 返回一个消息实体,
elif method=='post':
res = requests.post(url,data,headers=header,verify=False) # 返回一个消息实体
res.encoding = 'utf-8'
elif method=='put':
res = requests.put(url,data,headers=header,verify=False)
else:
print("method值错误!!!")
return res.json() #或返回消息实体不打印出来
# print("响应正文:",res)
# if __name__ == '__main__':#相当于java的main函数
# # url: 请求地址
# # param:传递参数 非必填参数 字典格式传递参数
# url = 'http://apis.juhe.cn/simpleWeather/query' # 聚合数据天气预报
# data = {"city": "成都", "key": "2d9abdfd0941fa7bd67ffdff674150e"}
# res=HttpRequest().hrrp_request(url,'post',data,)#实例化直接调用