Python的HTTP客户端请求 – GET,POST

Python的HTTP模块定义了一些类,它们提供了HTTP和HTTPS协议的客户端功能。在大多数程序中,HTTP模块并不直接使用,而是与urllib模块结合使用,用于处理URL连接和与HTTP请求的交互。今天我们将学习如何使用Python的HTTP客户端发送HTTP请求,然后解析响应状态并获取响应体数据。

Python的HTTP客户端

在这篇关于Python HTTP 模块的文章中,我们将尝试创建连接并发送HTTP请求,比如GET、POST和PUT。让我们开始吧。

建立HTTP连接

我们将从HTTP模块可以做的最简单的事情开始。使用此模块,我们可以轻松地进行HTTP连接。这是一个示例程序:

import http.client

connection = http.client.HTTPConnection('www.python.org', 80, timeout=10)
print(connection)
python http connection

请用 Python 进行 HTTP GET 请求

现在,我们将使用HTTP客户端从URL获取响应和状态。让我们看一段代码片段:

import http.client

connection = http.client.HTTPSConnection("www.scdev.com")
connection.request("GET", "/")
response = connection.getresponse()
print("Status: {} and reason: {}".format(response.status, response.reason))

connection.close()

遇到SSL:证书验证失败错误?

当我第一次执行上述程序时,我遇到了与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)
$ 
python ssl CERTIFICATE_VERIFY_FAILED fix
Python HTTP Client Ubuntu

从响应中获取标题列表

从我们收到的响应中,头部通常还包含有关从服务器返回的数据类型和响应状态的重要信息。我们可以从响应对象本身获取头部列表。让我们看一个稍微修改过的代码片段,这是上一个程序的变体。

import http.client
import pprint

connection = http.client.HTTPSConnection("www.scdev.com")
connection.request("GET", "/")
response = connection.getresponse()
headers = response.getheaders()
pp = pprint.PrettyPrinter(indent=4)
pp.pprint("Headers: {}".format(headers))
python http request 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 post

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)
python http request, python http put example

结论

在这堂课上,我们学习了使用http.client可以完成的简单HTTP操作。我们还可以使用SimpleHTTPServer模块创建Python HTTP服务器。

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds