Python Network Programming 简明教程
Python - Custom HTTP Requests
超文本传输协议 (HTTP) 是一种用于启用客户端和服务器之间通信的协议。它以客户端和服务器之间的请求-响应协议工作。请求设备称为客户端,发送响应的设备称为服务器。
The Hypertext Transfer Protocol (HTTP) is a protocol used to enable communications between clients and servers. It works as a request-response protocol between a client and server. The requesting device is known as the client and the device that sends the response is known as server.
urllib 是 Python 程序中用于处理 http 请求的传统 Python 库。但现在有了 urllib3,它做的比 urllib 还要多。我们导入 urllib3 库,看看 python 如何使用它来进行 http 请求并接收响应。我们可以通过选择请求方法来自定义请求类型。
The urllib is the traditional python library which is used in python programs to handle the http requests. But now there is urllib3 which does more than what urllib used to do. We import the urllib3 library to see how python can use it to make a http request and receive a response. We can customize the type of request by choosing the request method.
Pip install urllib3
Example
在以下示例中,我们使用处理 http 请求连接详细信息的 PoolManager() 对象。接下来,我们使用 request() 对象使用 POST 方法发出 http 请求。最后,我们还使用 json 库以 json 格式打印收到的值。
In the below example we use the PoolManager() object which takes care of the connection details of the http request. Next we use the request() object to make a http request with the POST method. Finally we also use the json library to print the received values in json format.
import urllib3
import json
http = urllib3.PoolManager()
r = http.request(
'POST',
'http://httpbin.org/post',
fields={'field': 'value'})
print json.loads(r.data.decode('utf-8'))['form']
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
{field': value'}
URL Using a Query
我们还可以传递查询参数来构建自定义 URL。在下面的示例中,请求方法使用查询字符串中的值来完成 URL,该 URL 可由 python 程序中的另一个函数进一步使用。
We can also pass query parameters to build custom URLs. In the below example the request method uses the values in the query string to complete the URL which can be further used by another function in the python program.
import requests
query = {'q': 'river', 'order': 'popular', 'min_width': '800', 'min_height': '600'}
req = requests.get('https://pixabay.com/en/photos/', params=query)
print(req.url)
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
https://pixabay.com/en/photos/?q=river&min_width=800&min_height=600&order=popular