我对 URLSession 没有太多经验,但我正在尝试进行 POST 调用,并且不断收到两个不同的错误。
这是我的函数:
func test() {
let parameters = ["username": "myUsername", "password": "myPassword"]
guard let url = URL(string: "https://example.com:443/Auth/") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
以下是我遇到的错误:
第一个有一个堆栈溢出链接:CredStore 执行查询错误。我添加了他们说要添加的代码,但我最终遇到了同样的错误。
CredStore - performQuery - Error copying matching creds. Error=-25300, query = {
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "/Auth/";
srvr = "example.com";
sync = syna;
}
我得到的下一个错误是:
<NSHTTPURLResponse: 0x600000b94180> { URL: https://example.com:443/Auth/ } { Status Code: 401, Headers {
"Content-Length" = (
31
);
"Content-Type" = (
"text/plain"
);
Date = (
"Mon, 24 Sep 2018 23:16:45 GMT"
);
"Www-Authenticate" = (
"Basic realm="/Auth/""
);
} }
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
我收到 401 未授权错误。我可以看到它给我 401 的唯一原因是它没有正确读取用户名/密码?我不是 100% 确定标题"用户名"和"密码"是否正确。实际的用户名和密码绝对正确。
对于遇到此问题的人:
我想出了什么问题:
func test() {
let username = "myUsername"
let password = "myPassword"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
let url = URL(string: "https://example.com:443/Auth/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic (base64LoginString)", forHTTPHeaderField: "Authorization")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
我的用户名和密码以纯文本形式发送。必须将我的凭据编码为 base64。