urllib3高级用法

除了基本的HTTP请求和响应处理功能,urllib3还提供了一些高级用法,包括:

1. 连接池管理:urllib3使用连接池管理HTTP连接,可以提高性能和效率。可以使用`urllib3.PoolManager`类创建连接池,例如:

```

http = urllib3.PoolManager()

response = http.request('GET', 'http://www.example.com')

```

2. SSL/TLS验证:可以使用`cert_reqs`和`ca_certs`参数来控制SSL/TLS验证。例如:

```

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs='/path/to/ca.pem')

response = http.request('GET', 'https://www.example.com')

```

3. 代理设置:可以使用`proxy_url`和`proxy_port`参数来设置代理。例如:

```

http = urllib3.ProxyManager('http://proxy.example.com:8080')

response = http.request('GET', 'http://www.example.com')

```

4. 文件上传:可以使用`fields`参数和`encode_multipart_formdata()`方法来上传文件。例如:

```

http = urllib3.PoolManager()

with open('/path/to/file', 'rb') as f:

    data = f.read()

    fields = {'file': ('filename', data)}

    encoded_data = urllib3.encode_multipart_formdata(fields)

    headers = {'Content-Type': encoded_data[1]}

    response = http.request('POST', 'http://www.example.com', body=encoded_data[0], headers=headers)

```

5. 超时设置:可以使用`timeout`参数来设置请求超时时间。例如:

```

http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=2.0, read=10.0))

response = http.request('GET', 'http://www.example.com')

```

以上是urllib3的一些高级用法,可以根据需要使用它们来完成更复杂的HTTP请求和响应处理任务。

猜你喜欢

转载自blog.csdn.net/weixin_59246157/article/details/129682848