我使用的是OAuth2.0 API,它可以很好地使用我的cURL命令行,但不能使用swift代码。
我阅读了其他StackOverflow帖子,但它不起作用:first和second。
实际上,我的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则不是。 我错了什么?
由于
答案 0 :(得分:2)
看起来您的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
包含=
或&
符号,则其解释方式会有所不同