ruby 第三方模块unirest使用

  • Creating Requests

    require 'unirest'
    response = Unirest.post 'http://httpbin.org/post',
                            headers:{ Accept:'application/json' },
                            parameters:{ age: 23, foo:'bar' }
    
    puts response.code # Status code
    puts response.headers # Response headers
    puts response.body # Parsed body
    puts response.raw_body # Unparsed body

     

  • File Uploads

    require 'unirest'
    Unirest.timeout(30)
    response = Unirest.post 'http://httpbin.org/post',
                            headers:{ Accept:'application/json' },
                            parameters:{ age:23, file:File.new(__dir__+'/test.text', 'rb') }
    puts response.body

     

  • Custom Entity Body

    require 'unirest'
    response = Unirest.post 'http://httpbin.org/post',
                            headers:{ Accept:'application/json' },
                            parameters:{ age:'value', foo:'bar' }.to_json # Converting the Hash to a JSON string
    puts response.body

     

  • Basic Authentication

    require 'unirest'
    response = Unirest.get 'http://httpbin.org/get', auth:{user:'username', password:'password'}
    puts response.body

     

  • Request

    Unirest.get(url, headers: {}, parameters: nil, auth:nil, &callback)
    Unirest.post(url, headers: {}, parameters: nil, auth:nil, &callback)
    Unirest.delete(url, headers: {}, parameters: nil, auth:nil, &callback)
    Unirest.put(url, headers: {}, parameters: nil, auth:nil, &callback)
    Unirest.patch(url, headers: {}, parameters: nil, auth:nil, &callback)
    • url (String) - Endpoint, address, or uri to be acted upon and requested information from.
    • headers (Object) - Request Headers as associative array or object
    • parameters (Array | Object | String) - Request Body associative array or object
    • callback (Function) - Optional; Asychronous callback method to be invoked upon result.

  • Response

    • code - HTTP Response Status Code (Example 200)
    • headers - HTTP Response Headers
    • body - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
    • raw_body - Un-parsed response body

  • Advanced Configuration

    Timeout

    Unirest.timeout(5) # 5s timeout

    Default Request Headers

    Unirest.default_header('Header1','Value1')
    Unirest.default_header('Header2','Value2')
    Unirest.clear_default_headers()

    User-Agent

    Unirest.user_agent("custom_user_agent")

    参考:http://unirest.io/ruby.html

转载于:https://www.cnblogs.com/wf0117/p/9000714.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值