使用Alamofire进行cURL请求

3

我正在尝试使用Alamofire完成这个cURL请求

curl -X POST -H "Content-Type: application/json" \
 --user "<client_id>:<client_secret>" \
 -d '{"grant_type": "client_credentials", "scope": "public"}' \
 'https://api.lyft.com/oauth/token'

我目前拥有:

  let plainString = "clientID:clientSecret" as NSString
    let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64String = plainData?.base64EncodedStringWithOptions([])

    let headers = [
        "Authorization": "Basic \(base64String)",
        "Content-Type": "application/json"
    ]

    let params = [
        "grant_type": "client_credentials",
        "scope": "public"
    ]

    Alamofire.request(.POST, "https://api.lyft.com/oauth/token", parameters: params, encoding: .JSON, headers: headers).responseJSON { response in
        debugPrint(response)
    }

我的代码返回了状态码400

我做错了什么?

提前感谢!

1个回答

2

问题已解决,

必须使用 .authenticate 方法

Alamofire.request(.POST, "https://api.lyft.com/oauth/token", parameters: params, encoding: .JSON, headers: headers).authenticate(user: "clientID", password: "clientSecret").responseJSON { response in
        debugPrint(response)
    }

非常感谢您!我必须将.POST更改为method: .post,并将.JSON更改为.JSONEncoding.default,才能使其与Alamofire 4.8.0 / Swift 9.4.1配合使用:Alamofire.request("https://api.lyft.com/oauth/token", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).authenticate(user: "clientID", password: "clientSecret").responseJSON { response in debugPrint(response) } - velkoon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接