首先让我说我非常是 Python 的新手,但我熟悉其他编程语言。在开始这个项目之前,我需要问几个问题。
我需要能够直接从 Python 发出 URL GET、PUT、POST 和 DELETE 请求。
我将为这些功能的特定用例编写一个库,我不希望用户必须安装外部库(如“请求”)。
最好的方法是什么,urllib.request?
谢谢你对我的教育。
最佳答案
I need to be able to make URL GET, PUT, POST, and DELETE requests straight out of Python. ... What is the best way to do this, urllib2?
自 urllib.request.urlopen()硬连接到 GET 或 POST,您将需要 http.client.HTTPConnection相反:
import http.client
import pprint
conn = http.client.HTTPConnection('www.jython.org')
c = conn.request('HEAD', '/index.html')
r = conn.getresponse()
pprint.pprint(r.getheaders())
print('Size of body:', len(r.read()))
这项技术让您“更接近金属”并提供更多控制,但它 失去了 urllib.request 及其各种高级服务(如跟随重定向)的所有便利。
关于Python URL 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601086/