Vapor文檔學習廿八: HTTP -Response

在接收的請求后通常要返回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部分。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容