Swift Alamofire:如何获取HTTP响应状态代码

编程入门 行业动态 更新时间:2024-10-24 09:18:52
本文介绍了Swift Alamofire:如何获取HTTP响应状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想针对请求失败(最好也是成功)检索HTTP响应状态代码(例如400、401、403、503等)。在这段代码中,我正在使用HTTP Basic执行用户身份验证,并希望能够向用户通知用户输入错误密码时身份验证失败。

I would like to retrieve the HTTP response status code (e.g. 400, 401, 403, 503, etc) for request failures (and ideally for successes too). In this code, I am performing user authentication with HTTP Basic and want to be able to message the user that authentication failed when the user mistypes their password.

Alamofire.request(.GET, "host/a/path").authenticate(user: "user", password: "typo") .responseString { (req, res, data, error) in if error != nil { println("STRING Error:: error:\(error)") println(" req:\(req)") println(" res:\(res)") println(" data:\(data)") return } println("SUCCESS for String") } .responseJSON { (req, res, data, error) in if error != nil { println("JSON Error:: error:\(error)") println(" req:\(req)") println(" res:\(res)") println(" data:\(data)") return } println("SUCCESS for JSON") }

不幸的是,产生的错误似乎并不表示HTTP状态代码409实际已收到:

Unfortunately, the error produced does not seem to indicate that an HTTP status code 409 was actually received:

STRING Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=host/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=host/a/path}) req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: host/a/path } res:nil data:Optional("") JSON Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=host/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=host/a/path}) req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: host/a/path } res:nil data:nil

此外,最好在发生错误时检索HTTP正文,因为我的服务器端会将错误的文本描述放在那里。

Additionally, it would be nice to retrieve the HTTP body when an error occurs because my server-side will put a textual description of the error there.

问题 是否可以在非2xx响应时检索状态代码? 是否可以在收到2xx响应时检索特定状态代码? 2xx响应? 是否可以在非2xx响应时检索HTTP正文?

Questions Is it possible to retrieve the status code upon a non-2xx response? Is it possible to retrieve the specific status code upon a 2xx response? Is it possible to retrieve the HTTP body upon a non-2xx response?

谢谢!

推荐答案

对于 Swift 3.x / Swift 4.0 / Swift 5.0 Alamofire> = 4.0 / Alamofire> = 5.0 的用户

For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0

response.response?.statusCode

更详细的示例:

More verbose example:

Alamofire.request(urlString) .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") var statusCode = response.response?.statusCode if let error = response.result.error as? AFError { statusCode = error._code // statusCode private switch error { case .invalidURL(let url): print("Invalid URL: \(url) - \(error.localizedDescription)") case .parameterEncodingFailed(let reason): print("Parameter encoding failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") case .multipartEncodingFailed(let reason): print("Multipart encoding failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") case .responseValidationFailed(let reason): print("Response validation failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") switch reason { case .dataFileNil, .dataFileReadFailed: print("Downloaded file could not be read") case .missingContentType(let acceptableContentTypes): print("Content Type Missing: \(acceptableContentTypes)") case .unacceptableContentType(let acceptableContentTypes, let responseContentType): print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)") case .unacceptableStatusCode(let code): print("Response status code was unacceptable: \(code)") statusCode = code } case .responseSerializationFailed(let reason): print("Response serialization failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") // statusCode = 3840 ???? maybe.. default:break } print("Underlying error: \(error.underlyingError)") } else if let error = response.result.error as? URLError { print("URLError occurred: \(error)") } else { print("Unknown error: \(response.result.error)") } print(statusCode) // the status code }

(Alamofire 4包含一个全新的错误系统,请查看此处了解详情)

(Alamofire 4 contains a completely new error system, look here for details)

对于 Swift 2.x 用户, Alamofire> = 3.0

Alamofire.request(.GET, urlString) .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") if let alamoError = response.result.error { let alamoCode = alamoError.code let statusCode = (response.response?.statusCode)! } else { //no errors let statusCode = (response.response?.statusCode)! //example : 200 } }

更多推荐

Swift Alamofire:如何获取HTTP响应状态代码

本文发布于:2023-11-26 08:06:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633310.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:状态   代码   Swift   Alamofire   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!