gpt4 book ai didi

swift - URLSession POST 调用

转载 作者:行者123 更新时间:2023-11-30 11:07:57 24 4
gpt4 key购买 nike

我对 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。

关于swift - URLSession POST 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com