【问题标题】:cURL request using Alamofire使用 Alamofire 的 cURL 请求
【发布时间】:2016-03-13 03:28:01
【问题描述】:

我正在尝试使用 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

我做错了什么?

提前致谢!

【问题讨论】:

    标签: ios swift curl alamofire


    【解决方案1】:

    解决了,

    必须使用 .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) }
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2016-03-08
    • 2017-06-10
    • 2019-04-14
    • 2015-07-26
    • 1970-01-01
    • 2016-06-11
    • 2020-02-10
    相关资源
    最近更新 更多