首页 > 解决方案 > 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'

为什么我不能将我的回复存储到一个简单的文本文件中?

标签: pythonpython-3.xpython-requestshttpresponse

解决方案


似乎您将模块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)

推荐阅读