我正在尝试创建 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/