ios - swift/alamofire/api token /缺少必需参数 : grant_type

标签 ios swift api twitter

我正在尝试创建 TwitterSearcher。

我的条件是

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

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

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

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

我已经引用其他文章尝试过一些方法,比如说

  • 将参数更改为 ["payload": "grant_type=client_credentials"]
  • 从 header 中删除“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")
    }  
}

希望大家能够帮助我。

最佳答案

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

或者

Alamofire直接支持Basic auth

看这个

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

并使用authorizationHeader作为alamofire中的请求 header

希望对你有帮助

关于ios - swift/alamofire/api token /缺少必需参数 : grant_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841071/

相关文章:

python - CSRF 攻击是否适用于 API?

javascript - saveAll() 有效但抛出错误

iOS 架构 i386 的 undefined symbol

ios - 从自定义 UIViewController 获取自定义 NavigationController 类

api - 对于具有 GET 语义的超大请求应该使用什么 HTTP 动词?

python - 开源英语词典 - Python - 库 - API

iOS - 创建页面 pdf

ios - 未调用准备函数 - swift 3

swift - 使 "NSManaged public var"成为可选的 bool 值

swift - 在方法参数中隐式解包可选闭包