我正在从输出一些 json 内容的 API 中检索数据。但是,当我尝试使用以下代码将数据存储到一个简单的文本文件中时:
import urllib3
import json
http = urllib3.PoolManager()
url = 'http://my/endpoint/url'
myheaders = {'Content-Type':'application/json'}
mydata = {'username':'***','password':'***'}
response = http.request('POST', url, body=json.dumps(mydata).encode('UTF-8'), headers=myheaders)
print(response.status_code)
data = response.json()
with open('data.json', 'w') as f:
json.dump(data, f)
我收到以下错误:
AttributeError: 'HTTPResponse' object has no attribute 'json'
因此,我还尝试使用带有以下代码的 response.text:
file = open('data.json', 'w')
file.write(response.text)
file.close()
但我也收到此错误:
AttributeError: 'HTTPResponse' object has no attribute 'text'
为什么我不能将我的回复存储到一个简单的文本文件中?