您的凭据不允许访问此资源Twitter API错误 [英] Your credentials do not allow access to this resource Twitter API Error

查看:388
本文介绍了您的凭据不允许访问此资源Twitter API错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究twitter api,其中一些api正在得到响应.但是statuses/home_timeline.json api和其他api没有得到响应.

I'm working on twitter api's, some of api's getting response. But statuses/home_timeline.json api and other api's not getting response.

出错:

{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}

我正在成功获取访问令牌,并将该访问令牌用于statuses/home_timeline.json和其他一些api.但是这些都超过了错误.我已经用我的帐户登录了.

I'm getting access token successfully and using that access token for statuses/home_timeline.json and some other api's. But these are getting above error. Already i logged in with my account.

我发现了很多网址,但我没有从这些网址中得到答案.

I found so many urls and i'm not getting answer from those urls.

我的访问令牌代码是:

//Get twitter access token
func getAccessToken() {

    //RFC encoding of ConsumerKey and ConsumerSecretKey
    let encodedConsumerKeyString:String = "f4k***********0".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    let encodedConsumerSecretKeyString:String = "OD**************ln".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    print(encodedConsumerKeyString)
    print(encodedConsumerSecretKeyString)
    //Combine both encodedConsumerKeyString & encodedConsumerSecretKeyString with " : "
    let combinedString = encodedConsumerKeyString+":"+encodedConsumerSecretKeyString
    print(combinedString)
    //Base64 encoding
    let data = combinedString.data(using: .utf8)
    let encodingString = "Basic "+(data?.base64EncodedString())!
    print(encodingString)
    //Create URL request
    var request = URLRequest(url: URL(string: "https://api.twitter.com/oauth2/token")!)  //oauth/access_token   oauth2/token
    request.httpMethod = "POST"
    request.setValue(encodingString, forHTTPHeaderField: "Authorization")
    request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
    let bodyData = "grant_type=client_credentials".data(using: .utf8)!
    request.setValue("\(bodyData.count)", forHTTPHeaderField: "Content-Length")
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
        print("error=\(String(describing: error))")
        return
        }

//            let responseString = String(data: data, encoding: .utf8)
//            let dictionary = data
//            print("dictionary = \(dictionary)")
//            print("responseString = \(String(describing: responseString!))")

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        do {
            let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
            print("Access Token response : \(response)")
//                print(response["access_token"]!)
//                self.accessToken = response["access_token"] as! String
            if let token = response["access_token"] {
                self.accessToken = token as! String
            }

        } catch let error as NSError {
            print(error)
        }
    }

    task.resume()
}

Twitter 签名代码:

Twitter signing code :

//Twitter signin
@IBAction func onClickTwitterSignin(_ sender: UIButton) {

    //Login and get session
    TWTRTwitter.sharedInstance().logIn { (session, error) in

        if (session != nil) {
            //Read data
            let name = session?.userName ?? ""
            print(name)
            print(session?.userID  ?? "")
            print(session?.authToken  ?? "")
            print(session?.authTokenSecret  ?? "")

 //                self.loadFollowers(userid: session?.userID ?? "")

 //                let userid = session?.userID ?? ""
 //                let screenName = session?.userName ?? ""
 //                if userid != "" && screenName != "" {



             self.getStatusesUserTimeline(accessToken:self.accessToken)


 //                }

            //Get user email id
            let client = TWTRAPIClient.withCurrentUser()
            client.requestEmail { email, error in
                if (email != nil) {
                    let recivedEmailID = email ?? ""
                    print(recivedEmailID)
                } else {
                    print("error--: \(String(describing: error?.localizedDescription))");
                }
            }
            //Get user profile image url's and screen name
            let twitterClient = TWTRAPIClient(userID: session?.userID)
            twitterClient.loadUser(withID: session?.userID ?? "") { (user, error) in
                print(user?.profileImageURL ?? "")
                print(user?.profileImageLargeURL ?? "")
                print(user?.screenName ?? "")
            }



            let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
            self.navigationController?.pushViewController(storyboard, animated: true)
        } else {
            print("error: \(String(describing: error?.localizedDescription))");
        }
    }

}

获取twitter statuses/home_timeline.json :(登录成功后,我将调用此函数)

Get twitter statuses/home_timeline.json : (I'm calling this function after login success)

func getStatusesUserTimeline(accessToken:String) {

    let userId = "10************56"
    let twitterClient = TWTRAPIClient(userID: userId)
    twitterClient.loadUser(withID: userId) { (user, error) in
        print(userId)
        print(user ?? "Empty user")
        if user != nil {


            //Get users timeline tweets
            var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json?")!)                


            request.httpMethod = "GET"
            request.setValue("Bearer "+accessToken, forHTTPHeaderField: "Authorization")
            print(request)

            let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
                }


                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }

                do {
                    let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String,Any>
                    print(response)
 //                        print((response["statuses"] as! Array<Any>).count)

                } catch let error as NSError {
                    print(error)
                }
            }

            task.resume()

        } else {
            print(error?.localizedDescription as Any)
        }
    }

}

推荐答案

检查权限,如下图所示.转到开发者帐户->仪表板->选择您的应用->权限.

Check permission as follow screenshot. Goto developer account -> Dashboard -> select your app -> Permissions.

是使用纯应用程序身份验证还是仅具有只读权限的应用程序?

Would it be the case that you are using app-only authentication, or an app which has only read-only permissions?

请确保您的应用具有读写访问权限或阅读,编写和直接发送消息访问权限

Please make sure your app has a read-write access OR Read, write, and direct messages access

这篇关于您的凭据不允许访问此资源Twitter API错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆