【python模块】Http.client

该文章已生成可运行项目,


Http.client介绍

http.client 是 Python 标准库中的一个模块,它提供了一个低级别的接口来发送 HTTP 请求和接收响应。这个模块主要针对 HTTP 协议的实现,并且可以用于创建更复杂的 HTTP 客户端。

基本用法

http.client 模块允许你发送各种 HTTP 请求,包括 GET, POST, PUT, DELETE 等。下面是每种请求类型的基本用法:

  • GET 请求

GET 请求用于从服务器检索信息。使用 http.client 发送 GET 请求的基本步骤如下:

import http.client

# 创建连接
conn = http.client.HTTPSConnection("www.example.com")

# 发送 GET 请求
conn.request("GET", "/resource")

# 获取响应
response = conn.getresponse()

# 检查状态码
if response.status == 200:
    # 成功
    data = response.read()
    print(data.decode("utf-8"))
else:
    print(f"Failed with status {response.status}")

# 关闭连接
conn.close()
  • POST 请求

POST 请求用于向服务器发送数据。这里是一个发送 POST 请求的例子:

import http.client
import json

# 创建连接
conn = http.client.HTTPSConnection("www.example.com")

# 构建请求体
payload = {
    "key1": "value1",
    "key2": "value2"
}
headers = {
    "Content-Type": "application/json"
}

# 发送 POST 请求
conn.request("POST", "/resource", body=json.dumps(payload), headers=headers)

# 获取响应
response = conn.getresponse()

# 检查状态码
if response.status == 200:
    # 成功
    data = response.read()
    print(data.decode("utf-8"))
else:
    print(f"Failed with status {response.status}")

# 关闭连接
conn.close()
  • PUT 请求

PUT 请求用于更新服务器上的资源。以下是使用 http.client 发送 PUT 请求的示例:

import http.client
import json

# 创建连接
conn = http.client.HTTPSConnection("www.example.com")

# 构建请求体
payload = {
    "key1": "new_value1",
    "key2": "new_value2"
}
headers = {
    "Content-Type": "application/json"
}

# 发送 PUT 请求
conn.request("PUT", "/resource", body=json.dumps(payload), headers=headers)

# 获取响应
response = conn.getresponse()

# 检查状态码
if response.status == 200:
    # 成功
    data = response.read()
    print(data.decode("utf-8"))
else:
    print(f"Failed with status {response.status}")

# 关闭连接
conn.close()
  • DELETE 请求

DELETE 请求用于删除服务器上的资源。以下是如何使用 http.client 发送 DELETE 请求:

import http.client

# 创建连接
conn = http.client.HTTPSConnection("www.example.com")

# 发送 DELETE 请求
conn.request("DELETE", "/resource")

# 获取响应
response = conn.getresponse()

# 检查状态码
if response.status == 200:
    # 成功
    data = response.read()
    print(data.decode("utf-8"))
else:
    print(f"Failed with status {response.status}")

# 关闭连接
conn.close()

在所有这些示例中,我们首先创建了一个 http.client.HTTPSConnectionhttp.client.HTTPConnection 对象来与服务器建立连接。然后,我们调用 request 方法来发送特定类型的 HTTP 请求。最后,我们通过 getresponse 方法获取服务器的响应,并检查状态码以判断请求是否成功。

高级用法

以下是一些使用 http.client 的高级用法:

  • 自定义 HTTP 方法

虽然 http.client 默认支持 GET, POST, PUT, DELETE 等方法,但你可以自定义任何合法的 HTTP 方法:

import http.client

conn = http.client.HTTPConnection("www.example.com")
conn.request("CUSTOM_METHOD", "/path", headers={})
response = conn.getresponse()
  • 处理 HTTP 错误
import http.client

try:
    conn = http.client.HTTPConnection("www.example.com")
    conn.request("GET", "/non-existent-page")
    response = conn.getresponse()
    response.raise_for_status()  # 如果响应状态不是 200,将抛出异常
except http.client.HTTPException as e:
    print(f"An error occurred: {e}")
finally:
    conn.close()
  • 处理重定向

http.client 默认不会自动处理重定向。如果你需要处理重定向,可以手动检查响应状态码并重新发送请求:

import http.client

conn = http.client.HTTPConnection("www.example.com")
conn.request("GET", "/redirected_page")

response = conn.getresponse()
while response.status // 100 == 3:  # HTTP 3xx is a redirect status code
    location = response.getheader("Location")
    conn.request("GET", location)
    response = conn.getresponse()

print(response.read())
  • 使用代理

要通过代理服务器发送请求,可以设置 tunnel 方法:

import http.client

conn = http.client.HTTPConnection("proxy.example.com:8080")
conn.set_tunnel("www.example.com")

conn.request("GET", "/")
response = conn.getresponse()
print(response.read())
  • 设置超时时间

http.client 允许设置连接和读取超时:

import http.client

conn = http.client.HTTPConnection("www.example.com", timeout=10)  # 设置连接超时为10秒
conn.request("GET", "/")
response = conn.getresponse()
response.read(1024)  # 可以设置读取超时,但需要使用socket的settimeout方法
  • 发送分块编码的数据

在发送大量数据时,可以使用分块编码(Chunked Transfer Encoding):

import http.client

conn = http.client.HTTPConnection("www.example.com")
conn.putrequest("POST", "/")
conn.putheader("Transfer-Encoding", "chunked")
conn.endheaders()

# 发送数据
data = b"This is chunk 1\nThis is chunk 2"
for chunk in data.split(b'\n'):
    conn.send(f"{len(chunk):x}\r\n".encode())  # 发送块大小
    conn.send(chunk + b"\r\n")  # 发送块数据
conn.send(b"0\r\n\r\n")  # 表示数据结束

response = conn.getresponse()
print(response.read())
  • 发送 multipart/form-data 数据

当上传文件时,通常会使用这种编码格式:

import http.client
import mimetypes
from io import BytesIO

def encode_multipart_formdata(fields, files):
    boundary = '----------ThIs_Is_tHe_bouNdaRY_$'
    crlf = '\r\n'
    l = []

    for (key, value) in fields.items():
        l.append('--' + boundary)
        l.append('Content-Disposition: form-data; name="%s"' % key)
        l.append('')
        l.append(value)

    for (filename, value) in files.items():
        l.append('--' + boundary)
        l.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (filename, filename))
        l.append('Content-Type: %s' % get_content_type(filename))
        l.append('')
        l.append(value.read())

    l.append('--' + boundary + '--')
    l.append('')
    body = crlf.join(l)
    content_type = 'multipart/form-data; boundary=%s' % boundary
    return content_type, body

def get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

fields = {'title': 'Test file'}
files = {'file': BytesIO(b'This is the content of the file')}

content_type, body = encode_multipart_formdata(fields, files)

conn = http.client.HTTPConnection("www.example.com")
conn.request("POST", "/upload", body, {'Content-Type': content_type})
response = conn.getresponse()
print(response.read())

天雨粟,夜鬼哭。

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值