swift - Swift - 将 cURL 转换为 Swift 请求
问题描述
我正在尝试使用外部 API 来下载数据。我需要将 cURL 翻译成 Swift。
这是卷曲
curl \
-X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
https://test.api.amadeus.com/v1/security/oauth2/token \
-d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"
我有以下代码
guard let url = URL(string: "https://api.lucidtech.ai/v0/receipts"),
let payload = "grant_type=client_credentials&client_id=myClienID&client_secret=myClientSecret".data(using: .utf8)
else
{
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue(" application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = payload
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print(str)
}
}.resume()
它不起作用。
我不知道如何包含 client_id 和 client_secret。
我怎样才能做到这一点?
解决方案
这是您可以使用的代码片段:
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
]
let postData = NSMutableData(data: "grant_type=client_credentials".data(using: String.Encoding.utf8)!)
postData.append("&client_id={client_id}".data(using: String.Encoding.utf8)!)
postData.append("&client_secret={client_secret}".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "https://test.api.amadeus.com/v1/security/oauth2/token")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
//parse your model here from `data`
}
})
dataTask.resume()
推荐阅读
- bash - 使用 SCP 的语法是否发生了变化?在较新的服务器上出现意外的文件名错误
- c++ - 下面的代码输出 1 和 0 但是我不知道为什么
- javascript - 在 React 中显示图像文件夹
- sockets - WiFiP2PManager 连接 WiFiP2PConfig - 将端口号传递给客户端?
- c++ - SIMD C++ AVX2 Intrinsics 获取具有 16 位整数的 __m256i 向量的总和
- google-apps-script - 对 directory.members.insert 的 API 调用失败并出现错误:找不到资源:groupKey
- android - 使用 XML 中的背景属性不会更改按钮颜色
- html - 当用户输入 x 时,如何让 x 数量的输入框出现?
- python - How to add a row to every group with pandas groupby?
- python - Creating list from Pandas dataframe row while preserving data types