OStack程序员社区-中国程序员成长平台

标题: ios - Alamofire API(Digest Access Authentication) 数据访问错误 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:12
标题: ios - Alamofire API(Digest Access 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 获取数据,

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



Best Answer-推荐答案


我是这样做的:

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

关于ios - Alamofire API(Digest Access Authentication) 数据访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50634697/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4