轻量级的HTTP请求客户端库:Unirest
jopen
10年前
Unirest 是一个支持多种开发语言包括:Node、Ruby、Java、PHP、Python、Objective-C、.NET等的轻量级 HTTP 请求客户端,适用于大部分程序。
- 实现
GET
,POST
,PUT
,PATCH
,DELETE
请求 - 包括同步和异步(非阻塞)请求
- 支持表单参数,文件上传和自定义body entities
- 支持gzip
- 支持基本身份验证本身
- 自定义超时
- 为每个请求定制默认headers(DRY)
- 对JSON响应自动JSON解析成本地对象
以下是Python实现的使用示例
创建请求
使用Unirest使用Python创建请求更简单:
response = unirest.post("http://httpbin.org/post", headers={ "Accept": "application/json" }, params={ "parameter": 23, "foo": "bar" }) response.code # The HTTP status code response.headers # The HTTP headers response.body # The parsed response response.raw_body # The unparsed response
异步请求
Python也支持异步请求,可以在其中定义一个回调函数,以及传递和调用时Unirest接收响应:
def callback_function(response): response.code # The HTTP status code response.headers # The HTTP headers response.body # The parsed response response.raw_body # The unparsed response thread = unirest.post("http://httpbin.org/post", headers={ "Accept": "application/json" }, params={ "parameter": 23, "foo": "bar" }, callback=callback_function)
文件上传
传输文件数据,您需要以可读r模式打开文件:
response = unirest.post("http://httpbin.org/post", headers={"Accept": "application/json"}, params={ "parameter": "value", "file": open("/tmp/file", mode="r") } )
自定义Entity Body
import json response = unirest.post("http://httpbin.org/post", headers={ "Accept": "application/json" }, params=json.dumps({ "parameter": "value", "foo": "bar" }) )
Note: For the sake of semplicity, even with custom entities in the body, the keyword argument is still params
(instead of data
for example). I'm looking for feedback on this.
基本的身份验证
Authenticating the request with basic authentication can be done by providing an auth
array like:
response = unirest.get("http://httpbin.org/get", auth=('username', 'password'))
请求
unirest.get(url, headers = {}, params = {}, auth = (), callback = None) unirest.post(url, headers = {}, params = {}, auth = (), callback = None) unirest.put(url, headers = {}, params = {}, auth = (), callback = None) unirest.patch(url, headers = {}, params = {}, auth = (), callback = None) unirest.delete(url, headers = {}, params = {}, auth = (), callback = None)
url
- Endpoint, address, or URI to be acted upon and requested information from in a string format.headers
- Request Headers as an associative arrayparams
- Request Body as an associative array or objectauth
- The Basic Authentication credentials as an arraycallback
- Asychronous callback method to be invoked upon result.
项目主页:http://www.open-open.com/lib/view/home/1415237017090