Python HTTP客户端请求– GET,POST
Python HTTP模块定义了提供HTTP和HTTPS协议客户端的类。
在大多数程序中,HTTP模块不是直接使用,而是与urllib模块组合在一起以处理URL连接以及与HTTP请求的交互。
今天,我们将学习如何使用Python HTTP客户端来触发HTTP请求,然后解析响应状态并获取响应主体数据。
Python HTTP客户端
在python HTTP模块的这篇文章中,我们将尝试尝试建立连接并发出GET,POST和PUT之类的HTTP请求。
让我们开始吧。
建立HTTP连接
我们将从HTTP模块可以做的最简单的事情开始。
我们可以使用此模块轻松建立HTTP连接。
这是一个示例程序:
import http.client connection = http.client.HTTPConnection('www.python.org', 80, timeout=10) print(connection)
Python HTTP GET
现在,我们将使用HTTP客户端从URL获取响应和状态。
让我们看一下代码片段:
import http.client connection = http.client.HTTPSConnection("www.theitroad.local") connection.request("GET", "/") response = connection.getresponse() print("Status: {} and reason: {}".format(response.status, response.reason)) connection.close()
在上面的脚本中,我们使用了URL并检查了连接对象的状态。
让我们看一下该程序的输出:完成连接对象后,请记住关闭连接。
另外,请注意,由于是通过HTTPS协议提供服务的,因此我们使用了HTTPSConnection来建立连接。
正在获取SSL:CERTIFICATE_VERIFY_FAILED错误?
当我第一次执行上述程序时,出现以下与SSL证书有关的错误。
$python3.6 http_client.py Traceback (most recent call last): File "http_client.py", line 4, in <module> connection.request("GET", "/") File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 401, in wrap_socket context=self, session=session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in init self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748) $
从输出中可以明显看出,它必须对SSL证书进行某些处理。
但是证书很好,所以必须与我的设置有关。
经过一番谷歌搜索后,我发现在MacOS上,我们需要运行Python安装目录中的Install Certificates.command
文件来解决此问题。
下图显示了此命令执行产生的输出,看起来好像正在安装建立SSL连接时要使用的最新证书。
请注意,我在Mac OS上收到此错误。
但是,在我的Ubuntu系统上,它运行良好。
Python HTTP客户端Ubuntu
从响应中获取标题列表
从收到的响应中,标头通常还包含有关从服务器发送回的数据类型以及响应状态的重要信息。
我们可以从响应对象本身获取标头列表。
让我们看一下代码片段,它是最后一个程序的少许修改版本:
import http.client import pprint connection = http.client.HTTPSConnection("www.theitroad.local") connection.request("GET", "/") response = connection.getresponse() headers = response.getheaders() pp = pprint.PrettyPrinter(indent=4) pp.pprint("Headers: {}".format(headers))
Python HTTP POST
我们也可以使用HTTP模块将数据发布到URL,然后返回响应。
这是一个示例程序:
import http.client import json conn = http.client.HTTPSConnection('www.httpbin.org') headers = {'Content-type': 'application/json'} foo = {'text': 'Hello HTTP #1 **cool**, and #1!'} json_data = json.dumps(foo) conn.request('POST', '/post', json_data, headers) response = conn.getresponse() print(response.read().decode())
Python HTTP PUT请求
当然,我们也可以使用HTTP模块本身执行PUT请求。
我们将使用最后一个程序本身。
让我们看一下代码片段:
import http.client import json conn = http.client.HTTPSConnection('www.httpbin.org') headers = {'Content-type': 'application/json'} foo = {'text': 'Hello HTTP #1 **cool**, and #1!'} json_data = json.dumps(foo) conn.request("PUT", "/put", json_data) response = conn.getresponse() print(response.status, response.reason)