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

问题描述 投票:0回答:1

我尝试使用 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 是一个内部错误,我也不认为这是服务器的问题。

swift api alamofire digest-authentication
1个回答
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)
    }
© www.soinside.com 2019 - 2024. All rights reserved.