HHTPResponse对象没有属性json

问题描述 投票:0回答:1

我正在从输出一些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'

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

python python-3.x python-requests httpresponse
1个回答
0
投票

似乎您将模块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)
© www.soinside.com 2019 - 2024. All rights reserved.