HTTP的客戶端用于向遠(yuǎn)程服務(wù)器發(fā)送請(qǐng)求。下面我們看一個(gè)簡(jiǎn)單的外部請(qǐng)求。
QuickStart
讓我們進(jìn)入一個(gè)簡(jiǎn)單的HTTP請(qǐng)求,這是Vapor的GET請(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`