python - HTTPResponse 对象没有属性 json

标签 python python-3.x python-requests httpresponse

我正在从输出一些 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 的代码混合使用了

requestsstatus_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)

关于python - HTTPResponse 对象没有属性 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61998724/

相关文章:

curl - 将curl 转换为python 请求

python - 无法用pip安装pycuda

python - 匹配多个数据帧之间的子字符串并在单独的列中求和加权值

python - haystack ElasticsearchDocumentStore 无法连接 Elasticsearch

python-3.x - 如何使用python函数迭代从另一个函数接收的文件

python - BeautifulSoup - 如何从 html 类中获取所有 <div> ?

python - python 中是否有与 Linq.Expressions.Expression 等效的东西?

python - 从 python 的 Queue.Queue 中删除最旧的项目(同步)

python - 通过 sqlalchemy 映射类在 MySQL JSON 字段中插入键而不执行查询

python - 无法解码 base64 编码的图像