【问题标题】:Alamofire API(Digest Access Authentication) data access errorAlamofire API(Digest Access Authentication) 数据访问错误
【发布时间】:2018-11-11 01:56:03
【问题描述】:

我尝试 Alamofire 与我的服务器 API 通信以获取 JSON 数据。 我的 API 使用摘要式访问身份验证,但我最初在面对服务器挑战时遇到了问题,并设法通过以下代码克服。

    let userNameValue = "username"
    let passwordValue = "password"
    let credential = URLCredential(user: userNameValue, password: passwordValue, persistence: .forSession)        
    let sessionMananager = Alamofire.SessionManager.default
    let request = sessionMananager.request("http://httpbin.org/basic-auth/\(userNameValue)/\(passwordValue)")
        .authenticate(usingCredential: credential)
        .responseJSON { response in
            print("Response: \(String(describing: response.response))") // http url response
            print("Result: \(response.result)")                         // response serialization result
    }

输出看起来像

    Response:   
     { Status Code: 500, Headers {
           Connection =     (
               close
           );  
           "Content-Length" =     (
                0
           );
           "Content-Type" =     (
                "text/html; charset=UTF-8"
           );
     } }
    Result: FAILURE 

经过一番搜索,我将 .responseJSON 更改为 .responseString,输出更改如下

    Response:   
     { Status Code: 500, Headers {
           Connection =     (
               close
           );  
           "Content-Length" =     (
                0
           );
           "Content-Type" =     (
                "text/html; charset=UTF-8"
           );  
     } }
    Result: SUCCESS

为了确保挑战得到处理,我输入了错误的密码并尝试使用 .responseString,它给出的输出是状态码:401。

需要建议

要从 API 获取数据,

即使 Status Code: 500 是内部错误,我也不认为是服务器的问题。

【问题讨论】:

  • 奇怪的是您的代码说“basic-auth”,而您正在谈论 Digest auth。你能检查一下吗?

标签: ios swift api alamofire digest-authentication


【解决方案1】:

我是这样做的:

let sessionMananager = Alamofire.SessionManager.default
    let credential = URLCredential(user: "bruce", password: "dickinson", persistence: .forSession)

    sessionMananager.request("https://httpbin.org/digest-auth/undefined/bruce/dickinson")
        .authenticate(usingCredential: credential)
        .responseJSON { response in
            print("Result: \(String(describing: response.response?.statusCode))")
            print(response.result)
            print(response.description)
    }

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2014-01-27
    • 2017-07-30
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多