在Python中,你可以使用内置的库或者第三方库来发送HTTP请求。以下是使用Python发送HTTP请求的一些方法:
内置库
使用`http.client`库
```python
import http.client
conn = http.client.HTTPConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data.decode("utf-8"))
conn.close()
使用`urllib`库
```python
import urllib.request
response = urllib.request.urlopen("http://www.example.com")
print(response.read().decode("utf-8"))
第三方库
使用`requests`库
```python
import requests
发送GET请求
response = requests.get("http://www.example.com")
print(response.text)
发送POST请求
data = {"key1": "value1", "key2": "value2"}
response = requests.post("http://www.example.com", data=data)
print(response.text)
发送带有headers的请求
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get("http://www.example.com", headers=headers)
print(response.text)
使用`urllib2`库(Python 2.x)
```python
import urllib2
response = urllib2.urlopen("http://www.example.com")
print(response.read().decode("utf-8"))
使用`httplib`库(Python 2.x)
```python
import httplib
conn = httplib.HTTPConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data.decode("utf-8"))
conn.close()
HTTP服务端
如果你想搭建一个HTTP服务端,可以使用Python的内置模块`http.server`:
```python
在当前目录启动HTTP服务器
import http.server
handler = http.server.SimpleHTTPRequestHandler
with http.server.HTTPServer(("", 8000), handler) as httpd:
print("Serving on port 8000...")
httpd.serve_forever()
以上代码会在当前目录启动一个HTTP服务器,监听8000端口。
设置HTTP代理
如果你需要设置HTTP代理,可以使用`requests`库的`proxies`参数:
```python
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080"
}
response = requests.get("http://example.org", proxies=proxies)
print(response.text)
以上代码通过设置代理服务器地址和端口,发送HTTP请求。
请根据你的需求选择合适的方法来发送HTTP请求或搭建HTTP服务端