Vapor文檔學(xué)習(xí)卅二: HTTP -Client

HTTP的客戶端用于向遠(yuǎn)程服務(wù)器發(fā)送請(qǐng)求。下面我們看一個(gè)簡(jiǎn)單的外部請(qǐng)求。

QuickStart

讓我們進(jìn)入一個(gè)簡(jiǎn)單的HTTP請(qǐng)求,這是VaporGET請(qǐng)求:

let query = ...
let spotifyResponse = try drop.client.get("https://api.spotify.com/v1/search?type=artist&q=\(query)")
print(spotifyR)

Clear Up

上面的url理解起來(lái)可能有點(diǎn)困難,我們使用query做下簡(jiǎn)單的清理:

try drop.client.get("https://api.spotify.com/v1/search", query: ["type": "artist", "q": query])

Continued

除了GET, Vapor還支持更多常見(jiàn)的HTTP功能:GET, POST, PUT, PATCH, DELETE。

POST as json

let jsonBytes = myJSON.makeBytes()
try drop.client.post("http://some-endpoint/json", headers: ["Auth": "Token my-auth-token"], body: .data(jsonBytes))

POST as x-www-form-urlencoded

try drop.client.post("http://some-endpoint", headers: [
  "Content-Type": "application/x-www-form-urlencoded"
], body: Body.data( Node([
  "email": "mymail@vapor.codes"
]).formURLEncoded())) 

Full Request

為了獲取其他功能或者自定義方法,可以直接使用底層的request函數(shù)。

public static func get(_ method: Method,
                       _ uri: String,
                       headers: [HeaderKey: String] = [:],
                       query: [String: CustomStringConvertible] = [:],
                       body: Body = []) throws -> Response

下面調(diào)用這個(gè)接口:

try drop.client.request(.other(method: "CUSTOM"), "http://some-domain", headers: ["My": "Header"], query: ["key": "value"], body: [])

Config

Config/clients.json文件中可以修改客戶端的配置。

TLS

可以禁用主機(jī)和證書驗(yàn)證。

Note: 修改這些配置時(shí)請(qǐng)格外小心。

{
    "tls": {
        "verifyHost": false,
        "verifyCertificates": false
    }
}

Mozilla

默認(rèn)情況下包含Mozilla證書來(lái)保證從安全站點(diǎn)獲取內(nèi)容。

{
    "tls": {
        "certificates": "mozilla"
    }
}

Advanced

除了我們的Droplet,我們還有手動(dòng)使用或與client進(jìn)行交互。以下是我們?cè)?code>Vapor中的默認(rèn)實(shí)現(xiàn):

let response = try Client<TCPClientStream>.get("http://some-endpoint/mine")

我們可能注意到的第一件事是將TCPClientStream作為通用值。 這將使得HTTP.Client在進(jìn)行請(qǐng)求時(shí)可以使用底層連接。 通過(guò)遵守底層ClientStream協(xié)議,HTTP.Client可以無(wú)縫地接收自定義實(shí)現(xiàn)的流。

Save Connection

到目前為止,我們都是通過(guò)類或者靜態(tài)函數(shù)與Client進(jìn)行交互,這允許我們?cè)谕瓿烧?qǐng)求后斷開(kāi)連接,大多數(shù)情況下我們推薦這樣使用。在一些高級(jí)情景下,我們可能需要重新連接,為此我們像下面那樣初始化客戶端并進(jìn)行多次請(qǐng)求。

let pokemonClient = try drop?.client.make(scheme: "http", host: "pokeapi.co")
for i in 0...1 {
    let response = try pokemonClient?.get(path: "/api/v2/pokemon/", query: ["limit": 20, "offset": i])
    print("response: \(response)")
}

ClientProtocol

此前,我們專注于內(nèi)置的HTTP.Client,但用戶還可以通過(guò)遵守HTTP.ClientProtocol協(xié)議來(lái)包含自定義的客戶端。 我們來(lái)看看如何實(shí)現(xiàn):

public protocol Responder {
    func respond(to request: Request) throws -> Response
}

public protocol Program {
    var host: String { get }
    var port: Int { get }
    var securityLayer: SecurityLayer { get }
    // default implemented
    init(host: String, port: Int, securityLayer: SecurityLayer) throws
}

public protocol ClientProtocol: Program, Responder {
    var scheme: String { get }
    var stream: Stream { get }
    init(scheme: String, host: String, port: Int, securityLayer: SecurityLayer) throws
}

通過(guò)實(shí)現(xiàn)這些基本功能,我們可以立即訪問(wèn)我們上面查看的公共的ClientProtocolapi。

Customize Droplet

如果我們引入了一個(gè)遵守HTTP.ClientProtocol的自定義的client,我們可以把它傳給Droplet而不會(huì)改變應(yīng)用的底層行為。
示例:

let drop = Droplet()

drop.client = MyCustomClient.self

之后你對(duì)drop.client的所有調(diào)用都會(huì)使用MyCustomClient.self

drop.client.get(... // uses `MyCustomClient`
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,351評(píng)論 25 708
  • 第一章 Nginx簡(jiǎn)介 Nginx是什么 沒(méi)有聽(tīng)過(guò)Nginx?那么一定聽(tīng)過(guò)它的“同行”Apache吧!Ngi...
    JokerW閱讀 33,039評(píng)論 24 1,002
  • 這個(gè)一個(gè)為了給大家謀福利、存干貨、提高工作學(xué)習(xí)效率的(新手向)平臺(tái)>_< 文章主要是起一個(gè)拋磚迎玉的作用。所以有時(shí)...
    xuing閱讀 209評(píng)論 0 0
  • 一場(chǎng)春雨讓我燥郁凌亂的??安靜滋潤(rùn)起來(lái)。雖然這場(chǎng)春雨有點(diǎn)兒冷。人們描述春雨最普及的莫過(guò)于“春雨貴如油…”這句了。...
    鶯歌兒閱讀 411評(píng)論 0 0

友情鏈接更多精彩內(nèi)容