使用 Alamofire.download() 请求时如何从响应正文中获取错误消息
How to get error message from response body when use Alamofire.download() request
AF.download(url, parameters: params, to: destination)
.validate(statusCode: [200])
.response { response in
switch response.result {
case .success(let url):
print("ok", url)
case .failure(let err):
print(err.localizedDescription)
}
}
当服务器响应某些错误代码如 4xx、5xx 时,它会打印“响应状态代码不可接受:xxx。”,但我想要响应正文中的详细消息(服务器在出错时发送纯文本),我阅读一些 post 说我们可以使用“response.data”检索响应消息,但如果使用 AF.download 方法,则没有“数据”属性 和响应对象(Alamofire.AFDownloadResponse).那么,有什么办法可以解决吗?
这来自 Alamofire 源代码;
The debug textual representation used when written to an output stream, which includes (if available) a summary of the URLRequest
, the request's headers and body (if decodable as a String
below 100KB); the HTTPURLResponse
's status code, headers, and body; the duration of the network and serialization actions; and the Result
of serialization.
响应调试描述有状态码信息。所以,响应应该有状态码信息。
我也是在查看源码的时候看到这部分;
static func description(of response: HTTPURLResponse) -> String {
"""
[Response]:
[Status Code]: \(response.statusCode)
\(DebugDescription.description(for: response.headers).indentingNewlines())
"""
}
所以,response.status应该给你想要的。祝你好运。
Alamofire 的 DownloadResponse
包含一个 fileURL: URL?
属性 可用于从磁盘加载下载的数据,即使验证或其他操作在响应中产生失败结果。
AF.download(url, parameters: params, to: destination)
.validate(statusCode: [200])
.response { response in
switch response.result {
case .success(let url):
print("ok", url)
case .failure(let err):
print(err.localizedDescription)
}
}
当服务器响应某些错误代码如 4xx、5xx 时,它会打印“响应状态代码不可接受:xxx。”,但我想要响应正文中的详细消息(服务器在出错时发送纯文本),我阅读一些 post 说我们可以使用“response.data”检索响应消息,但如果使用 AF.download 方法,则没有“数据”属性 和响应对象(Alamofire.AFDownloadResponse).那么,有什么办法可以解决吗?
这来自 Alamofire 源代码;
The debug textual representation used when written to an output stream, which includes (if available) a summary of the
URLRequest
, the request's headers and body (if decodable as aString
below 100KB); theHTTPURLResponse
's status code, headers, and body; the duration of the network and serialization actions; and theResult
of serialization.
响应调试描述有状态码信息。所以,响应应该有状态码信息。
我也是在查看源码的时候看到这部分;
static func description(of response: HTTPURLResponse) -> String {
"""
[Response]:
[Status Code]: \(response.statusCode)
\(DebugDescription.description(for: response.headers).indentingNewlines())
"""
}
所以,response.status应该给你想要的。祝你好运。
Alamofire 的 DownloadResponse
包含一个 fileURL: URL?
属性 可用于从磁盘加载下载的数据,即使验证或其他操作在响应中产生失败结果。