SDK包(Ruby版)

2018-11-21 21:27 更新

推薦使用Gem

推薦使用:PhalApi SDK for Ruby 。

6.6.1 使用說(shuō)明

將框架目錄下的 ./SDK/Ruby/PhalApiClient 目錄中的全部代碼拷貝到項(xiàng)目里面即可使用。

6.6.2 代碼示例

如下是使用的代碼場(chǎng)景片段。

首先,我們需要導(dǎo)入SDK包:

#demo.rb

require_relative './PhalApiClient/phalapi_client'

a_client = PhalApi::Client.create.withHost('http://demo.phalapi.net')
a_response = a_client.withService('Default.Index').withParams('username', 'dogstar').withTimeout(3000).request()

puts a_response.ret, a_response.data, a_response.msg

6.6.3 運(yùn)行效果

運(yùn)行后,可以看到:

200
{"title"=>"Hello World!", "content"=>"dogstar您好,歡迎使用PhalApi!", "version"=>"1.2.1", "time"=>1445741092}

6.5.4 更多調(diào)用

當(dāng)需要重復(fù)調(diào)用時(shí),需要先進(jìn)行 重置操作 ,如:

#one more time
a_response = a_client.reset \
    .withService("User.GetBaseInfo") \
    .withParams("user_id", "1") \
    .request

puts a_response.ret, a_response.data, a_response.msg

當(dāng)請(qǐng)求有異常時(shí),返回的 ret!= 200,如:

#illegal request
a_response = a_client.reset.withService('XXXX.noThisMethod').request

puts a_response.ret, a_response.data, a_response.msg

以上的輸出為:

--------------------
400
非法請(qǐng)求:接口服務(wù)XXXX.noThisMethod不存在

6.6.5 擴(kuò)展你的過(guò)濾器和結(jié)果解析器

(1)擴(kuò)展過(guò)濾器

當(dāng)服務(wù)端接口需要接口簽名驗(yàn)證,或者接口參數(shù)加密傳送,或者壓縮傳送時(shí),可以實(shí)現(xiàn)此過(guò)濾器,以便和服務(wù)端操持一致。

當(dāng)需要擴(kuò)展時(shí),分兩步。首先,需要實(shí)現(xiàn)過(guò)濾器接口:

class MyFilter < PhalApi::ClientFilter 
        def filter(service, *params)
            #TODO ...
        end
}

然后設(shè)置過(guò)濾器:

a_response = PhalApi::Client.create.withHost('http://demo.phalapi.net') \
       .withFilter(MyFilter.new) \
       # ... \
       .request

(2)擴(kuò)展結(jié)果解析器

當(dāng)返回的接口結(jié)果不是JSON格式時(shí),可以重新實(shí)現(xiàn)此接口。

當(dāng)需要擴(kuò)展時(shí),同樣分兩步。類(lèi)似過(guò)濾器擴(kuò)展,這里不再贅述。

6.6.6 一如既往的單元測(cè)試

最后,附一張單元測(cè)試運(yùn)行的效果圖:


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)