我正在尝试使用以下代码将数据发布到网站的api:
import requests as r
import json
load={"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9",
"content-length": "40",
"content-type": "application/json",
"origin": "www.mysite.com",
"referer": "www.mysite.com",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.37",
}
pd={"version"="1.0"}
ro = r.post("api.mysite.com", headers=json.dumps(load),data=pd)
print(ro.status_code, ro.reason)
但是我一直收到此错误:
Traceback (most recent call last):
File "test.py", line 18, in <module>
ro = r.post("https://api.mysite.com", headers=json.dumps(load),data=pd)
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 61, in reques
t
return session.request(method=method, url=url, **kwargs)
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 516, in
request
prep = self.prepare_request(req)
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 459, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 315, in prepare
self.prepare_headers(headers)
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 447, in prepare_headers
for header in headers.items():
AttributeError: 'str' object has no attribute 'items'
我检查了负载的类型及其字典。 任何帮助表示赞赏。
答案 0 :(得分:3)
正如您所说,您的加载对象已经是一个字典(可以通过json序列化,并且具有items属性)
headers = json.dumps(load)
json.dumps方法是将加载对象JSON编码为一个字符串(没有项方法)
尝试
headers = load
代替