Python urllib.request';请求';对象没有属性';getcode';阅读

Python urllib.request';请求';对象没有属性';getcode';阅读,python,python-3.x,urllib,urllib3,Python,Python 3.x,Urllib,Urllib3,我的打印语句出错 “请求”对象没有属性“getcode”且已读取 sample = '[{{ "t": "{0}", "to": "{1}", "evs": "{2}", "fds": {3} }}]' response = urllib.request.Request(REST_API_URL, sample.encode('utf-8')) print("Response: HTTP {0} {1}\n".format(response.getcode(), response.read(

我的
打印
语句出错
“请求”对象没有属性“getcode”且已读取

sample = '[{{ "t": "{0}", "to": "{1}", "evs": "{2}", "fds": {3} }}]'

response = urllib.request.Request(REST_API_URL, sample.encode('utf-8'))

print("Response: HTTP {0} {1}\n".format(response.getcode(), response.read()))

urllib.request.request
urllib.request
模块用于抽象请求的类。要发出HTTP请求,应使用
urllib.request.urlopen

response = urllib.request.urlopen(REST_API_URL, sample.encode('utf-8'))

您命名的变量
response
实际上是
urllib.request.request
的一个实例。如果需要响应,需要首先发送请求,这可以使用
urllib.request.urlopen()
完成

但是,我建议您尝试更易于使用的模块,而不是了解如何使用python urllib.request。例如,您的代码可以这样表示:

import requests
resp = requests.post(REST_API_URL, json=[{{ "t": "{0}", "to": "{1}", "evs": "{2}", "fds": {3} }}])
print("Response: HTTP {} {}".format(resp.statuscode, resp.content)

那是因为它没有!是的,你能建议它的替代方案吗…你有下面的答案。。。但是为了将来的参考,您可以在您的案例中使用
dir(o)
print(dir(response))
当然!谢谢你!