在接收的請(qǐng)求后通常要返回Response
作為響應(yīng)找田。我們做外部請(qǐng)求時(shí)也要接收響應(yīng)對(duì)象毒姨。
public let status: Status
public var headers: [HeaderKey: String]
public var body: Body
public var data: Content
Status
http請(qǐng)求狀態(tài)冤竹,比如.ok == 200
表示請(qǐng)求成功宿礁。
Headers
與請(qǐng)求相關(guān)的請(qǐng)求頭信息案铺。如果準(zhǔn)備對(duì)外部請(qǐng)求做出響應(yīng),你可以添加自己的keys梆靖。
let contentType = response.headers["Content-Type"]
或者
let response = response ...
response.headers["Content-Type"] = "application/json"
response.headers["Authorization"] = ... my auth token
Extending Headers
使用擴(kuò)展優(yōu)化代碼:
extension HTTP.KeyAccessible where Key == HeaderKey, Value == String {
var customKey: String? {
get {
return self["Custom-Key"]
}
set {
self["Custom-Key"] = newValue
}
}
}
"Custom-Key"
已經(jīng)包含在代碼中控汉,可以直接獲缺仕小:
let customKey = response.headers.customKey
// or
let request = ...
response.headers.customKey = "my custom value"
Body
承載Response的主體內(nèi)容。主要通過兩種方式在初始化時(shí)進(jìn)行設(shè)置姑子。
BodyRepresentable
可以轉(zhuǎn)換為字節(jié)的實(shí)例:
let response = Response(status: .ok, body: "some string")
上面的String
會(huì)自動(dòng)轉(zhuǎn)換為body乎婿。你自己的類型也可以這樣使用。
BytesDirectory
直接使用Bytes array:
let response = Response(status: .ok, body: .data(myArrayOfBytes))
Chunked
發(fā)送一個(gè)HTTP.Response
的代碼塊街佑,我們可以通過傳遞閉包發(fā)送body部分谢翎。
let response = Response(status: .ok) { chunker in
for name in ["joe", "pam", "cheryl"] {
sleep(1)
try chunker.send(name)
}
try chunker.close()
}
Note:在
chunk
銷毀之前一定要調(diào)用close()
方法。
Content
從響應(yīng)中獲取content和從Request中獲取一樣:
let pokemonResponse = try drop.client.get("http://pokeapi.co/api/v2/pokemon/")
let names = pokemonResponse.data["results", "name"]?.array
JSON
直接使用json數(shù)據(jù)”
let json = response.json["hello"]
Key Paths
使用方法同Request
中的Key Paths部分沐旨。