欢迎访问宙启技术站
智能推送

如何在Python中发送HTTP请求

发布时间:2024-01-13 08:01:10

在Python中发送HTTP请求可以使用Python的内置库urllib、第三方库requests或者http.client等。以下是使用这三种库发送HTTP请求的示例。

1. 使用urllib发送HTTP请求的示例:

import urllib.request

# 发送GET请求
response = urllib.request.urlopen('https://api.example.com')
print(response.read().decode('utf-8'))

# 发送POST请求
data = {'key1': 'value1', 'key2': 'value2'}
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url='https://api.example.com', data=data, method='POST')
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))

2. 使用requests发送HTTP请求的示例:

import requests

# 发送GET请求
response = requests.get('https://api.example.com')
print(response.text)

# 发送POST请求
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com', data=data)
print(response.text)

3. 使用http.client发送HTTP请求的示例:

import http.client

# 发送GET请求
conn = http.client.HTTPSConnection('api.example.com')
conn.request('GET', '/')
response = conn.getresponse()
print(response.read().decode())

# 发送POST请求
params = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
conn.request('POST', '/', urllib.parse.urlencode(params), headers)
response = conn.getresponse()
print(response.read().decode())

以上是三种常用的发送HTTP请求的方法,选择其中一种根据个人偏好和项目需求使用即可。综合比较而言,requests库在易用性和功能丰富性方面更胜一筹,因此在实际开发中较为常用。