使用requests库发起post请求处理json的两种方式
今天在使用python的request库访问合作方的java接口时候遇到的问题。
- curl命令测试接口,通过
- 使用requests库发起post请求
手动将字典转为json字符串
data = json.dumps(data,ensure_ascii=False)
得到报错:
response = requests.post(url, headers=headers, data=data)
File "/data/anaconda3/lib/python3.9/site-packages/requests/api.py", line 117, in post
return request('post', url, data=data, json=json, **kwargs)
File "/data/anaconda3/lib/python3.9/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/data/anaconda3/lib/python3.9/site-packages/requests/sessions.py", line 529, in request
resp = self.send(prep, **send_kwargs)
File "/data/anaconda3/lib/python3.9/site-packages/requests/sessions.py", line 645, in send
r = adapter.send(request, **kwargs)
File "/data/anaconda3/lib/python3.9/site-packages/requests/adapters.py", line 440, in send
resp = conn.urlopen(
File "/data/anaconda3/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlo
pen
httplib_response = self._make_request(
File "/data/anaconda3/lib/python3.9/site-packages/urllib3/connectionpool.py", line 398, in _mak
e_request
conn.request(method, url, **httplib_request_kw)
File "/data/anaconda3/lib/python3.9/site-packages/urllib3/connection.py", line 239, in request
super(HTTPConnection, self).request(method, url, body=body, headers=headers)
File "/data/anaconda3/lib/python3.9/http/client.py", line 1279, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/data/anaconda3/lib/python3.9/http/client.py", line 1324, in _send_request
body = _encode(body, 'body')
File "/data/anaconda3/lib/python3.9/http/client.py", line 167, in _encode
raise UnicodeEncodeError(
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 79-90: Body ('疑似多记血透
监测收费时长') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in U
TF-8.
需要再次编码为utf-8
data = data.encode("utf-8")
最终整体代码
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
import json
url = "****/api/querybtchInfos"
data = {
"btch_type" : "1",
"MODL_VER" : "v20240801",
"admdvs": "500108",
"MODEL_NAME": "模型名称描述"
}
headers = {
'Content-Type': 'application/json'
}
#将data转为json格式的字符串
data = json.dumps(data,ensure_ascii=False)
data = data.encode("utf-8")
print(data)
response = requests.post(url, headers=headers, data=data)
print(response.status_code)
print(response.text)
或者直接传递json格式,requests库会自动进行json.dumps
import requests
url = "****/api/querybtchInfos"
data = {
"btch_type" : "1",
"MODL_VER" : "v20240801",
"admdvs": "500108",
"MODEL_NAME": "模型名称描述"
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, json=data)
print(response.status_code)
print(response.text)