| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
9年前发布

轻量级的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 array
  • params - Request Body as an associative array or object
  • auth - The Basic Authentication credentials as an array
  • callback - Asychronous callback method to be invoked upon result.

 

项目主页:http://www.open-open.com/lib/view/home/1415237017090

 

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1415237017090.html
Unirest 网络工具包