python - HTTPResponse 对象没有属性 json
问题描述
我正在从输出一些 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'
为什么我不能将我的回复存储到一个简单的文本文件中?
解决方案
似乎您将模块requests
代码与模块代码混合在一起urllib3
requests
有status_code
。.text
, .content
,.json()
但urllib3
没有
要求
import requests
url = 'https://httpbin.org/post'
mydata = {'username': '***', 'password': '***'}
response = requests.post(url, json=mydata)
print(response.status_code)
data = response.json()
print(data)
with open('data.json', 'wb') as f:
f.write(response.content)
#json.dump(data, f)
urllib3
import urllib3
import json
http = urllib3.PoolManager()
url = 'https://httpbin.org/post'
myheaders = {'Content-Type': 'application/json'}
mydata = {'username': '***', 'password': '***'}
response = http.request('POST', url, body=json.dumps(mydata).encode('UTF-8'), headers=myheaders)
#print(dir(response))
print(response.status)
data = json.loads(response.data)
print(data)
with open('data.json', 'wb') as f:
f.write(response.data)
推荐阅读
- c# - 带有 MySQL 的 Windows 窗体 C# 实体框架 6
- java - 找不到 GlideApp
- android - React Native 0.57.7 - Android 构建在任务中失败:app:mergeReleaseResources
- javascript - 在 ReactJS 中,使用 Reactstrap,我希望我的警报保持在它开始的屏幕上的同一个位置
- java - 定制肥皂响应
- symfony - Symfony 4.2.3 - 用户注册电子邮件域时设置 ManyToOne Id
- spring-boot - 如何以编程方式获得 Start-Class?
- apache-kafka - Kafka时差最后两条记录,KSQL还是其他?
- html - 为什么填充会影响背景图像是否显示?
- css - Google 字体的字体变体数字