【问题标题】:swift/alamofire/api token/ Missing required parameter: grant_typeswift/alamofire/api 令牌/缺少必需参数:grant_type
【发布时间】:2019-09-14 09:37:50
【问题描述】:

我正在尝试创建 TwitterSearcher。

我的条件是

  • 使用仅限应用的身份验证
  • 标准搜索 API
  • 使用 Alamofire、SwiftyJSON

正如你们中的一些人所知,在搜索推文之前,您需要获得一个令牌才能访问 Twitter。

我对使用 API 本身还是很陌生,但我几乎没有实现一些代码。 但是,我在获取令牌的过程中遇到了下面的错误响应。

{
  "errors" : [
    {
      "code" : 170,
      "label" : "forbidden_missing_parameter",
      "message" : "Missing required parameter: grant_type"
    }
  ]
}

我已经尝试了一些参考其他文章的方法,比如说

  • 将参数更改为 ["payload" : "grant_type=client_credentials"]
  • 从标题中删除“content_type”

虽然我没有抓住这两个的意思,但是错误还是在发生。

import Foundation
import Alamofire
import SwiftyJSON

protocol SearchUserApi {
    func getToken()
    func getTweets(content: String)
}

class APIOperator: SearchUserApi {

     var accessToken: String?
     let tokenApi = "https://api.twitter.com/oauth2/token"
     let api = "https://api.twitter.com/1.1/search/tweets.json"
     let consumerKey = "---"
     let consumerSecret = "---"



    func getToken() {
        let credentials = "\(consumerKey):\(consumerSecret)".data(using: String.Encoding.utf8)!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        let headers = [
            "Authorization" : "Basic \(credentials)",
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        ]
        let params: [String : AnyObject] = ["grant_type": "client_credentials" as AnyObject]


        Alamofire.request(
            tokenApi,
            method: .post,
            parameters: params,
            encoding: JSONEncoding.default,
            headers: headers
            )
            .responseJSON { (response) in
                guard let object = response.result.value else {
                    print("Getting token is failed")
                    return
                }
                let json = JSON(object)
                print(json)
        }


    }

    func getTweets(content: String) {
       print("not yet")
    }  
}

希望你们能帮帮我。

【问题讨论】:

    标签: ios swift api twitter


    【解决方案1】:

    您可以尝试使用URLEncoding.httpBody 而不是JSONEncoding.default

    Alamofire 直接支持基本认证

    看到这个

    https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication

    这是来自文档的示例代码

    let user = "user"
    let password = "password"
    
    let credential = URLCredential(user: user, password: password, persistence: .forSession)
    
    Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
        .authenticate(usingCredential: credential)
        .responseJSON { response in
            debugPrint(response)
    }
    

    并在 alamofire 中使用 authorizationHeader 作为请求标头

    希望对你有帮助

    【讨论】:

    • 感谢您的评论。我实际上阅读了 Github,但我不明白参数和标题去了哪里。在使用authorizationHeader的情况下,您不必像上面那样添加Authorization、content_type和grant_type吗?在这种情况下,用户和密码意味着 consumerKey 和 Secret?因为它仅限应用程序。
    • 顺便说一句 URLEncoding.httpBody 显然有效!谢谢。
    • @lyn 我看到了其他问题,发现 grant_type 应该作为字符串而不是 HTTP 正文传递。如果有帮助,请将我的回答标记为已接受。
    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2019-12-11
    • 2012-01-02
    • 2014-06-29
    相关资源
    最近更新 更多