首页 > 解决方案 > 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。

我怎样才能做到这一点?

标签: swifthttprequest

解决方案


这是您可以使用的代码片段:


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()


推荐阅读