gpt4 book ai didi

ios - 将 cURL 命令行转换为 Swift cURL 不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 07:11:53 25 4
gpt4 key购买 nike

我使用 OAuth2.0 API,它在我的 cURL 命令行中运行良好,但在 swift 代码中运行不佳。

我阅读了这些其他 StackOverflow 帖子,但它不起作用:firstsecond .

其实我的curl命令是:curl -X POST --data "grant_type=client_credentials&client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET"https://api.myapp.fr/oauth/token

我的快速代码是:

        var dataStr: String!
let request = NSMutableURLRequest(url: NSURL(string: "https://api.myapp.fr/oauth/token")! as URL)

let session = URLSession.shared
request.httpMethod = "POST"

request.setValue("plain/text", forHTTPHeaderField: "Content-Type")

let params = ["grant_type" : "client_credentials",
"client_id" : "MY_CLIENT_ID",
"client_secret" : "MY_CLIENT_SECRET"] as Dictionary<String, String>
let httpData = NSKeyedArchiver.archivedData(withRootObject: params)
request.httpBody = httpData

let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

dataStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String!
print("Data -> ")
print(dataStr)
})

task.resume()

在第一种情况下,请求的格式正确,而对于 swift 则不然。我做错了什么?

谢谢

最佳答案

看起来您的 API 需要主体中的 key=value 样式。试试这个:

let url = URL(string: "https://api.myapp.fr/oauth/token")!
let params = [
"grant_type" : "client_credentials",
"client_id" : "MY_CLIENT_ID",
"client_secret" : "MY_CLIENT_SECRET"
]
let paramString = params.map {"\($0)=\($1)"}.joined(separator: "&") // for clarity and debugging

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = paramString.data(using: .utf8)

URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("empty data")
return
}

let dataString = String(data: data, encoding: .utf8)
print(dataString)
}.resume()

这显然不处理特殊字符编码。例如,如果 MY_CLIENT_SECRET 包含一个 =& 符号,它将被非常不同地解释

关于ios - 将 cURL 命令行转换为 Swift cURL 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44457686/

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