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

使用Python的from_httplib()函数发送GET和POST请求的方法

发布时间:2024-01-06 15:16:26

使用Python发送HTTP请求的方法之一是使用httplib库。httplib库提供了HTTPConnection类,可以创建与服务器的HTTP连接,并使用request()方法发送请求。

以下是使用httplib库发送GET和POST请求的方法和示例代码。

1. 导入httplib库:

import httplib

2. 创建HTTPConnection对象:

conn = httplib.HTTPConnection("example.com")  # 替换为实际的服务器地址

3. 发送GET请求:

conn.request("GET", "/path/to/resource")  # 替换为实际的资源路径
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)

4. 发送POST请求:

headers = {"Content-type": "application/json"}  # 替换为实际的请求头
payload = '{"key1": "value1", "key2": "value2"}'  # 替换为实际的请求体
conn.request("POST", "/path/to/resource", payload, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)

下面是一个完整的例子,发送了一个GET请求和一个POST请求:

import httplib

conn = httplib.HTTPConnection("example.com")

# 发送GET请求
conn.request("GET", "/path/to/resource")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)

# 发送POST请求
headers = {"Content-type": "application/json"}
payload = '{"key1": "value1", "key2": "value2"}'
conn.request("POST", "/path/to/resource", payload, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)

conn.close()

注意:httplib库在Python 3中已被替代为http.client,但用法类似。如果使用Python 3,请使用http.client代替httplib