在接收的請求后通常要返回Response作為響應。我們做外部請求時也要接收響應對象。
public let status: Status
public var headers: [HeaderKey: String]
public var body: Body
public var data: Content
Status
http請求狀態(tài),比如.ok == 200表示請求成功。
Headers
與請求相關的請求頭信息。如果準備對外部請求做出響應,你可以添加自己的keys。
let contentType = response.headers["Content-Type"]
或者
let response = response ...
response.headers["Content-Type"] = "application/json"
response.headers["Authorization"] = ... my auth token
Extending Headers
使用擴展優(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"已經包含在代碼中,可以直接獲?。?/p>
let customKey = response.headers.customKey
// or
let request = ...
response.headers.customKey = "my custom value"
Body
承載Response的主體內容。主要通過兩種方式在初始化時進行設置。
BodyRepresentable
可以轉換為字節(jié)的實例:
let response = Response(status: .ok, body: "some string")
上面的String會自動轉換為body。你自己的類型也可以這樣使用。
BytesDirectory
直接使用Bytes array:
let response = Response(status: .ok, body: .data(myArrayOfBytes))
Chunked
發(fā)送一個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銷毀之前一定要調用close()方法。
Content
從響應中獲取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部分。