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 是内部错误,我也不认为是服务器的问题。
解决方案
我是这样做的:
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)
}
推荐阅读
- reactjs - npm 运行构建错误 - 无法读取未定义的属性“toLowerCase”
- django-rest-framework - 我们可以在不使用 django 中的媒体文件夹来存储动态创建的 .docx 文件的情况下创建任何文件夹/目录吗
- selenium - 同时使用 Selenium 运行多个 Chromedriver 浏览器窗口:需要多少 vCPU 和多少 GB RAM?
- javascript - 如何从 Node.js 服务器向客户端发送结合随机数的图像
- ios - 将 MLMultiArray 转换为 C#/.Net 等价物?Xamarin IOS
- c# - System.ArgumentOutOfRangeException:容量小于当前大小。(参数“值”)
- r - 如何使用 openxlsx 修改 Excel 中的现有工作表(具有相同的布局)?
- python - 在熊猫中拆分对象 dtype 列
- numpy - Numba 是否支持内置 python 函数,例如`setitem`
- .net - 恢复项目时出现 Dotnet maui 问题