Alamofire API(摘要访问身份验证)数据访问错误

时间:2018-06-01 00:52:50

标签: ios swift api alamofire digest-authentication

我尝试使用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获取数据

即使状态码:500是内部错误,我也不认为这是服务器的问题。

1 个答案:

答案 0 :(得分:0)

我是这样的:

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)
    }
相关问题