輕量級的HTTP請求客戶端庫:Unirest
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.baiduhome.net/lib/view/home/1415237017090
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!