gpt4 book ai didi

python - 我如何克服 Python http.client.HTTPResponse 对象?

转载 作者:行者123 更新时间:2023-12-04 14:30:53 28 4
gpt4 key购买 nike

我试图从以下代码中获得来自 url 的响应。
我正在使用 Python 3.x

from urllib.request import urlopen

url_getallfolders = 'https://qa.wittyparrot.com/alfresco/service/acrowit/userfolderinfo?access_token=TICKET_83361146b0e140f48ba404c3d8457452a92e117f'
x = urlopen(url_getallfolders)
print(x)

我收到以下错误:
<http.client.HTTPResponse object at 0x030304B0>

我什至尝试过 urllib.urlopen:
x = urllib.urlopen(url_getallfolders)
print(x)

然后我得到这个错误:
NameError: name 'urllib' is not defined

请帮助。提前致谢

最佳答案

您没有收到错误,而是收到了预期的响应对象。如果您想从响应中访问数据,那么您需要从该对象中读取数据,或者检查标题和状态代码。

读取响应正文数据非常简单:

x = urlopen(url_getallfolders)
data = x.read()

来自 urllib.request.urlopen() documentation :

For http and https urls, this function returns a http.client.HTTPResponse object which has the following HTTPResponse Objects methods.



我在哪里使用了 HTTPResponse.read() method以上。

请注意,结果将是编码字节,如果您需要文本,您仍然需要解码该文本。您调用的 URL 返回 JSON,因此您可能希望将其解码为 Python:
import json

x = urlopen(url_getallfolders)
raw_data = x.read()
encoding = x.info().get_content_charset('utf8') # JSON default
data = json.loads(raw_data.decode(encoding))

之后您可以访问 key ,例如 'error' , 'errorList' , 'respList''warning' .

关于python - 我如何克服 Python http.client.HTTPResponse 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32169421/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com