我没有太多的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 Perform Query error。我添加了他们说要添加的代码,但最终还是遇到了相同的错误。
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。