加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:06:50 所属栏目:百科 来源:网络整理
导读:我想检索请求失败的HTTP响应状态代码(例如400,401,403,503等)(最好是成功)。在此代码中,我使用HTTP Basic执行用户身份验证,并希望能够在用户输入密码错误时通知用户身份验证失败。 Alamofire.request(.GET,"https://host.com/a/path").authenticate(use
我想检索请求失败的HTTP响应状态代码(例如400,401,403,503等)(最好是成功)。在此代码中,我使用HTTP Basic执行用户身份验证,并希望能够在用户输入密码错误时通知用户身份验证失败。
Alamofire.request(.GET,"https://host.com/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,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:

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

另外,当发生错误时检索HTTP主体是很好的,因为我的服务器端会在那里放置一个错误的文本描述。

问题
是否可以在非2xx响应时检索状态代码?
是否可以在2xx响应时检索特定的状态代码?
是否可以在非2xx响应时检索HTTP主体?

谢谢!

对于Alamofire> = 4.0的Swift 3.x用户
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..
                }

                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包含一个全新的错误系统,查看here的详细信息)

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

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
             }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读