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

时间:2017-06-09 12:20:18

标签: ios swift curl

我使用的是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则不是。 我错了什么?

由于

1 个答案:

答案 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包含=&符号,则其解释方式会有所不同