📜  记录 HTTPURLRESPONSE swift (1)

📅  最后修改于: 2023-12-03 14:57:38.149000             🧑  作者: Mango

记录 HTTPURLResponse Swift

在 Swift 中,可以通过 HTTPURLResponse 类来获取 HTTP 请求的响应。HTTPURLResponse 是 NSHTTPURLResponse 的子类,它提供了从 HTTP 响应中获取很多有用的信息的方法。

获取 HTTP 状态码
if let httpResponse = response as? HTTPURLResponse {
    let statusCode = httpResponse.statusCode
    print("status code: \(statusCode)")
}
获取响应头
if let httpResponse = response as? HTTPURLResponse {
    let headers = httpResponse.allHeaderFields
}
获取响应体

一个 HTTPURLResponse 有一个可选属性 data,用来存储响应数据。下面的例子解析到一个字符串变量中。

if let data = data, let httpResponse = response as? HTTPURLResponse {
    let responseString = String(data: data, encoding: .utf8)
    print("response: \(responseString)")
}
记录所有 HTTP 请求和响应

通过将请求和响应关联在一起记录它们是非常有用的。以下是如何用一个简单的 Swift 类来记录所有 HTTP 请求和响应的例子。

class HttpClient {
    
    static let shared = HttpClient()
    
    func sendRequest(url: URL, method: String, completionHandler: @escaping (_ result: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {

        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            
            if let error = error {
                print("Error: \(error.localizedDescription)")
            }
            
            if let httpResponse = response as? HTTPURLResponse {
                let statusCode = httpResponse.statusCode
                let headers = httpResponse.allHeaderFields
                let responseString = String(data: data!, encoding: .utf8)!
                
                print("----")
                print("Method: \(method)")
                print("URL: \(url.absoluteString)")
                print("Status Code: \(statusCode)")
                print("Headers: \(headers)")
                print("Response: \(responseString)")
            }
            
            completionHandler(data, response, error)
        }
        task.resume()
    }
}

以上是一个快速的参考,如有需要,需要根据特定的应用程序进行自定义。