繁体   English   中英

使用oAuth 1.0的Twitter搜索API身份验证错误

[英]Twitter Search API authentication error using oAuth 1.0

我正在使用Twitter搜索api根据用户输入的关键字来获取最近的推文,响应中出现以下错误,

 {"errors":[{"code":215,"message":"Bad Authentication data."}]}

我按照这个这个继该OAuth协议。 请指出我做错了什么。

我在使用oAuth 1.0验证API标头时遇到问题

func getRecentTweets(query : String)
{

    // The below are the oAuth Parameters for header
    let timeStamp = Date().toMillis()
    let oauthNonce = Utils.randomString(length: 32)
    let urlEncodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
    var paramterString = "q=\(urlEncodedQuery)&result_type=recent&lang=en&oauth_consumer_key=\(oauthConsumerKey)&oauth_nonce=\(oauthNonce )&oauth_timestamp=\(timeStamp ?? 0)&oauth_token=\(oauthToken)&oauth_version=\(oauthVersion)"

    paramterString = paramterString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
    var baseUrl = "https://api.twitter.com/1.1/search/tweets.json"
    baseUrl = baseUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
    let signature_base_string = "GET&\(baseUrl)&\(paramterString)"
    let consumerSecretEncoded = oauthConsumerSecret.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
    let tokenSecretEncoded = oauthAccessSecret.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
    let signing_key = "\(consumerSecretEncoded)&\(tokenSecretEncoded)"

    let oauthSignature = signature_base_string.hmac(key: signing_key)



    let headers = [
        "Authorization": "OAuth oauth_consumer_key=\"\(oauthConsumerKey)\",oauth_token=\"\(oauthToken)\",oauth_signature_method=\"\(oauthSignatureMethod)\",oauth_timestamp=\"\(timeStamp ?? 0)\",oauth_nonce=\"\(oauthNonce )\",oauth_version=\"\(oauthVersion)\",oauth_signature=\"\(oauthSignature)\""
    ]

    let request = NSMutableURLRequest(url: NSURL(string: "https://api.twitter.com/1.1/search/tweets.json?q=\(urlEncodedQuery)&result_type=recent&lang=en")! as URL)

    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {

        } else {
            self.parseData(data)
        }
    })

    dataTask.resume()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM