HTTP
的客戶端用于向遠程服務器發送請求。下面我們看一個簡單的外部請求。
QuickStart
讓我們進入一個簡單的HTTP請求,這是Vapor
的GET
請求:
let query = ...
let spotifyResponse = try drop.client.get("https://api.spotify.com/v1/search?type=artist&q=\(query)")
print(spotifyR)
Clear Up
上面的url理解起來可能有點困難,我們使用query
做下簡單的清理:
try drop.client.get("https://api.spotify.com/v1/search", query: ["type": "artist", "q": query])
Continued
除了GET
, Vapor還支持更多常見的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
函數。
public static func get(_ method: Method,
_ uri: String,
headers: [HeaderKey: String] = [:],
query: [String: CustomStringConvertible] = [:],
body: Body = []) throws -> Response
下面調用這個接口:
try drop.client.request(.other(method: "CUSTOM"), "http://some-domain", headers: ["My": "Header"], query: ["key": "value"], body: [])
Config
在Config/clients.json
文件中可以修改客戶端的配置。
TLS
可以禁用主機和證書驗證。
Note: 修改這些配置時請格外小心。
{
"tls": {
"verifyHost": false,
"verifyCertificates": false
}
}
Mozilla
默認情況下包含Mozilla證書來保證從安全站點獲取內容。
{
"tls": {
"certificates": "mozilla"
}
}
Advanced
除了我們的Droplet
,我們還有手動使用或與client
進行交互。以下是我們在Vapor
中的默認實現:
let response = try Client<TCPClientStream>.get("http://some-endpoint/mine")
我們可能注意到的第一件事是將TCPClientStream
作為通用值。 這將使得HTTP.Client
在進行請求時可以使用底層連接。 通過遵守底層ClientStream
協議,HTTP.Client
可以無縫地接收自定義實現的流。
Save Connection
到目前為止,我們都是通過類或者靜態函數與Client進行交互,這允許我們在完成請求后斷開連接,大多數情況下我們推薦這樣使用。在一些高級情景下,我們可能需要重新連接,為此我們像下面那樣初始化客戶端并進行多次請求。
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
此前,我們專注于內置的HTTP.Client
,但用戶還可以通過遵守HTTP.ClientProtocol
協議來包含自定義的客戶端。 我們來看看如何實現:
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
}
通過實現這些基本功能,我們可以立即訪問我們上面查看的公共的ClientProtocol
api。
Customize Droplet
如果我們引入了一個遵守HTTP.ClientProtocol
的自定義的client,我們可以把它傳給Droplet
而不會改變應用的底層行為。
示例:
let drop = Droplet()
drop.client = MyCustomClient.self
之后你對drop.client
的所有調用都會使用MyCustomClient.self
:
drop.client.get(... // uses `MyCustomClient`