Twitter的集成:请求被理解,但它已被拒绝。这code是当请求被拒绝,由于更新的限制使用 [英] Twitter Integration : The request is understood, but it has been refused. This code is used when requests are being denied due to update limits

查看:2149
本文介绍了Twitter的集成:请求被理解,但它已被拒绝。这code是当请求被拒绝,由于更新的限制使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/5121921/twitter-api-rate-limits-for-posting-updates\">Twitter API速率限制为上发布更新


我已经集成的HttpClient-4.0.1.jar,路标-commonhttp4-1.2.1.1.jar,路标 - 核心1.2.1.1.jar,twitter4j核心在我的应用程序集成的Twitter -2.1.11.jar文件..

在code是:

 公共类AndroidTwitterSample延伸活动{私人共享preferences preFS;
私人最终处理程序mTwitterHandler =新的处理程序();
私人TextView的loginStatus;
字符串消息=斐伊川;
最终的Runnable mUpdateTwitterNotification =新的Runnable(){
    公共无效的run(){
        Toast.makeText(getBaseContext(),鸣叫送!,Toast.LENGTH_LONG).show();
    }
};@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    这preFS = preferenceManager.getDefaultShared preferences(本)。    loginStatus =(的TextView)findViewById(R.id.login_status);
    巴顿鸣叫=(按钮)findViewById(R.id.btn_tweet);
    按钮clearCredentials =(按钮)findViewById(R.id.btn_clear_credentials);    tweet.setOnClickListener(新View.OnClickListener(){
        / **
         *发送鸣叫。如果用户未认证的情况还没有高音单元,他会通过浏览器重定向
         *到Twitter的登录页面。一旦用户通过验证,他会授权的Andr​​oid应用程序发送
         *上的用户代表的tweet。
         * /
        公共无效的onClick(视图v){
            如果(TwitterUtils.isAuthenticated(preFS)){
                sendTweet();
            }其他{
                意图I =新意图(getApplicationContext(),prepareRequestTokenActivity.class);
                i.putExtra(tweet_msg,getTweetMsg());
                startActivity(ⅰ);
            }
        }
    });    clearCredentials.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            clearCredentials();
            updateLoginStatus();
        }
    });
}@覆盖
保护无效onResume(){
    super.onResume();
    updateLoginStatus();
}公共无效updateLoginStatus(){
    loginStatus.setText(登录到微博:+ TwitterUtils.isAuthenticated(preFS));
}
私人字符串getTweetMsg(){
    返回消息;
}公共无效sendTweet(){
    线程t =新的Thread(){
        公共无效的run(){            尝试{
                TwitterUtils.sendTweet(preFS,getTweetMsg());
                mTwitterHandler.post(mUpdateTwitterNotification);
            }赶上(例外前){
                ex.printStackTrace();
            }
        }    };
    t.start();
}私人无效clearCredentials(){
    共享preferences preFS = preferenceManager.getDefaultShared preferences(本);
    最终的编辑器编辑= prefs.edit();
    edit.remove(OAuth.OAUTH_TOKEN);
    edit.remove(OAuth.OAUTH_TOKEN_SECRET);
    edit.commit();
}
}

常量类:

 公共类常量{公共静态最后弦乐CONSUMER_KEY =&LT;密钥gt;中;
公共静态最后弦乐CONSUMER_SECRET =&LT;&秘密GT;公共静态最后弦乐REQUEST_URL =htt​​ps://api.twitter.com/oauth/request_token;
公共静态最后弦乐ACCESS_URL =htt​​ps://api.twitter.com/oauth/access_token;
公共静态最后弦乐AUTHORIZE_URL =htt​​ps://api.twitter.com/oauth/authorize;公共静态最后弦乐OAUTH_CALLBACK_SCHEME =X-oauthflow-微博;
公共静态最后弦乐OAUTH_CALLBACK_HOST =回调;
公共静态最后弦乐OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME +://+ OAUTH_CALLBACK_HOST;
}

该OAuthRequestToken类:

 公共类OAuthRequestTokenTask扩展的AsyncTask&LT;太虚,太虚,太虚&GT; {最后的字符串标记=的getClass()的getName()。
私人上下文的背景下;
私人OAuthProvider供应商;
私人消费OAuthConsumer;/ **
 *
 *我们通过OAuth的消费者和提供者。
 *
 * @参数方面
 *必须能够启动的意图,启动浏览器。
 * @参数提供商
 *本OAuthProvider对象
 * @参数消费
 *本OAuthConsumer对象
 * /
公共OAuthRequestTokenTask(上下文的背景下,消费OAuthConsumer,OAuthProvider提供商){
    this.context =背景;
    this.consumer =消费;
    this.provider =供应商;
}/ **
 *
 *检索的OAuth请求令牌和present浏览器用户授权令牌。
 *
 * /
@覆盖
保护无效doInBackground(虚空...... PARAMS){    尝试{
        Log.i(TAG,从谷歌服务器检索请求令牌);
        最终字符串URL = provider.retrieveRequestToken(消费者,Constants.OAUTH_CALLBACK_URL);
        Log.i(TAG,啪浏览器在authorize URL:+网址);
        意向意图=新意图(Intent.ACTION_VIEW,Uri.parse(URL))setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND)。
        context.startActivity(意向);
    }赶上(例外五){
        Log.e(TAG,OAuth的过程中出现错误检索请求令牌,E);
    }    返回null;
}}

prepareRequestTokenActivity:

 公共类prepareRequestTokenActivity延伸活动{最后的字符串标记=的getClass()的getName()。私人消费OAuthConsumer;
私人OAuthProvider供应商;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    尝试{
        this.consumer =新CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET);
        this.provider =新CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
    }赶上(例外五){
        Log.e(TAG错误创建消费者/提供者,E);
    }    Log.i(TAG,启动任务检索请求令牌。);
    新OAuthRequestTokenTask(这一点,消费者,供应商).execute();
}/ **
 *当OAuthRequestTokenTask完成(用户已授权请求令牌)调用。
 *回调URL将在这里截获。
 * /
@覆盖
公共无效onNewIntent(意向意图){
    super.onNewIntent(意向);
    共享preferences preFS = preferenceManager.getDefaultShared preferences(本);
    最后乌里URI = intent.getData();
    如果(URI = NULL&放大器;!&安培; uri.getScheme()等于(Constants.OAUTH_CALLBACK_SCHEME)){
        Log.i(TAG,回调收到:+ URI);
        Log.i(TAG,检索访问令牌);
        新RetrieveAccessTokenTask(这一点,消费者,供应商,preFS).execute(URI);
        完();
    }
}公共类RetrieveAccessTokenTask扩展的AsyncTask&LT;开放的,太虚,太虚&GT; {    私人上下文的背景下;
    私人OAuthProvider供应商;
    私人消费OAuthConsumer;
    私人共享preferences preFS;    公共RetrieveAccessTokenTask(上下文的背景下,消费OAuthConsumer,OAuthProvider提供商,共享preferences preFS){
        this.context =背景;
        this.consumer =消费;
        this.provider =供应商;
        这preFS = preFS。
    }
    / **
     *检索oauth_verifier,并存储的OAuth和oauth_token_secret
     *为未来的API调用。
     * /
    @覆盖
    保护无效doInBackground(URI ... PARAMS){
        最后乌里URI =参数[0];
        最后弦乐oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);        尝试{
            provider.retrieveAccessToken(消费者,oauth_verifier);            最终的编辑器编辑= prefs.edit();
            edit.putString(OAuth.OAUTH_TOKEN,consumer.getToken());
            edit.putString(OAuth.OAUTH_TOKEN_SECRET,consumer.getTokenSecret());
            edit.commit();            字符串标记= prefs.getString(OAuth.OAUTH_TOKEN,);
            字符串的秘密= prefs.getString(OAuth.OAUTH_TOKEN_SECRET,);            consumer.setTokenWithSecret(令牌,密);
            context.startActivity(新意图(上下文,AndroidTwitterSample.class));            executeAfterAccessTokenRetrieval();            Log.i(TAG的OAuth - 访问令牌取自);        }赶上(例外五){
            Log.e(TAG的OAuth - 访问令牌检索错误,E);
        }        返回null;
    }
    私人无效executeAfterAccessTokenRetrieval(){
        弦乐味精= getIntent()getExtras()的getString(tweet_msg)。;
        尝试{
            TwitterUtils.sendTweet(preFS,味精);
        }赶上(例外五){
            Log.e(TAG的OAuth - 错误发送到Twitter,E);
        }
    }
}}

TwitterUtils:

 公共类TwitterUtils {公共静态布尔isAuthenticated(共享preferences preFS){    字符串标记= prefs.getString(OAuth.OAUTH_TOKEN,);
    字符串的秘密= prefs.getString(OAuth.OAUTH_TOKEN_SECRET,);    一个的accessToken =新的accessToken(令牌,密);
    叽叽喳喳叽叽喳喳=新TwitterFactory()的getInstance()。
    twitter.setOAuthConsumer(Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(一);    尝试{
        twitter.getAccountSettings();
        返回true;
    }赶上(TwitterException E){
        返回false;
    }
}公共静态无效sendTweet(共享preferences preFS,弦乐味精)抛出异常{
    字符串标记= prefs.getString(OAuth.OAUTH_TOKEN,);
    字符串的秘密= prefs.getString(OAuth.OAUTH_TOKEN_SECRET,);    一个的accessToken =新的accessToken(令牌,密);
    叽叽喳喳叽叽喳喳=新TwitterFactory()的getInstance()。
    twitter.setOAuthConsumer(Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(一);
    twitter.updateStatus(MSG);
}
}

问题是后2鸣叫,这是给我一个例外:

  W / System.err的(5104)403:请求被理解,但它已被拒绝。一位随行的错误信息会解释为什么。当请求被拒绝,由于更新的限制这code使用(http://support.twitter.com/forums/10711/entries/15364)。
    W / System.err的(5104):错误 - 状态是重复的。
    W / System.err的(5104):请求 - /1/statuses/update.json
    W / System.err的(5104):相关讨论可以在Internet上:
     W / System.err的(5104):http://www.google.co.jp/search?q=15bb6564或
     W / System.err的(5104):http://www.google.co.jp/search?q=010f3e5b
     W / System.err的(5104):TwitterException {异常code = [15bb6564-010f3e5b],状态code = 403,retryAfter = 0,rateLimitStatus = NULL,版本2.1.11 =}
      W / System.err的(5104):在twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:199)
      W / System.err的(5104):在twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:75)
      W / System.err的(5104):在twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:112)
      W / System.err的(5104):在twitter4j.Twitter.updateStatus(Twitter.java:593)
    W / System.err的(5104):在com.ecs.android.sample.twitter.TwitterUtils.sendTweet(TwitterUtils.java:38)
      W / System.err的(5104):在com.ecs.android.sample.twitter.AndroidTwitterSample $ 4.run(AndroidTwitterSample.java:84)


解决方案

从你的错误消息:

 错误 - 状态是重复的。

这意味着你不能鸣叫同一消息的两倍。
如果你已经在推特消息 HI 不能再次鸣叫它(至少在该日为不知道)。您将获得状态是重复错误

Possible Duplicate:
Twitter API rate limits for posting updates

I have Integrated twitter in my application by Integrating "httpclient-4.0.1.jar", "signpost-commonhttp4-1.2.1.1.jar","signpost-core-1.2.1.1.jar", "twitter4j-core-2.1.11.jar" files..

The code is:

   public class AndroidTwitterSample extends Activity {

private SharedPreferences prefs;
private final Handler mTwitterHandler = new Handler();
private TextView loginStatus;
String message="Hii";
final Runnable mUpdateTwitterNotification = new Runnable() {
    public void run() {
        Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    this.prefs = PreferenceManager.getDefaultSharedPreferences(this);

    loginStatus = (TextView)findViewById(R.id.login_status);
    Button tweet = (Button) findViewById(R.id.btn_tweet);
    Button clearCredentials = (Button) findViewById(R.id.btn_clear_credentials);

    tweet.setOnClickListener(new View.OnClickListener() {
        /**
         * Send a tweet. If the user hasn't authenticated to Tweeter yet, he'll be redirected via a browser
         * to the twitter login page. Once the user authenticated, he'll authorize the Android application to send
         * tweets on the users behalf.
         */
        public void onClick(View v) {
            if (TwitterUtils.isAuthenticated(prefs)) {
                sendTweet();
            } else {
                Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg",getTweetMsg());
                startActivity(i);
            }
        }
    });

    clearCredentials.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            clearCredentials();
            updateLoginStatus();
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    updateLoginStatus();
}

public void updateLoginStatus() {
    loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}


private String getTweetMsg() {
    return message;
}   

public void sendTweet() {
    Thread t = new Thread() {
        public void run() {

            try {
                TwitterUtils.sendTweet(prefs,getTweetMsg());
                mTwitterHandler.post(mUpdateTwitterNotification);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    };
    t.start();
}

private void clearCredentials() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Editor edit = prefs.edit();
    edit.remove(OAuth.OAUTH_TOKEN);
    edit.remove(OAuth.OAUTH_TOKEN_SECRET);
    edit.commit();
}
}

The Constants class:

  public class Constants {

public static final String CONSUMER_KEY = "<key>";
public static final String CONSUMER_SECRET= "<secret>";

public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";

public static final String  OAUTH_CALLBACK_SCHEME   = "x-oauthflow-twitter";
public static final String  OAUTH_CALLBACK_HOST     = "callback";
public static final String  OAUTH_CALLBACK_URL      = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;


}

The OAuthRequestToken class:

public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;

/**
 * 
 * We pass the OAuth consumer and provider.
 * 
 * @param   context
 *          Required to be able to start the intent to launch the browser.
 * @param   provider
 *          The OAuthProvider object
 * @param   consumer
 *          The OAuthConsumer object
 */
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
    this.context = context;
    this.consumer = consumer;
    this.provider = provider;
}

/**
 * 
 * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
 * 
 */
@Override
protected Void doInBackground(Void... params) {

    try {
        Log.i(TAG, "Retrieving request token from Google servers");
        final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
        Log.i(TAG, "Popping a browser with the authorize URL : " + url);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
        context.startActivity(intent);
    } catch (Exception e) {
        Log.e(TAG, "Error during OAUth retrieve request token", e);
    }

    return null;
}

}

PrepareRequestTokenActivity:

 public class PrepareRequestTokenActivity extends Activity {

final String TAG = getClass().getName();

private OAuthConsumer consumer; 
private OAuthProvider provider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
        this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
    } catch (Exception e) {
        Log.e(TAG, "Error creating consumer / provider",e);
    }

    Log.i(TAG, "Starting task to retrieve request token.");
    new OAuthRequestTokenTask(this,consumer,provider).execute();
}

/**
 * Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
 * The callback URL will be intercepted here.
 */
@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent); 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Uri uri = intent.getData();
    if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
        Log.i(TAG, "Callback received : " + uri);
        Log.i(TAG, "Retrieving Access Token");
        new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
        finish();   
    }
}

public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;
    private SharedPreferences prefs;

    public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
        this.context = context;
        this.consumer = consumer;
        this.provider = provider;
        this.prefs=prefs;
    }


    /**
     * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret 
     * for future API calls.
     */
    @Override
    protected Void doInBackground(Uri...params) {
        final Uri uri = params[0];
        final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

        try {
            provider.retrieveAccessToken(consumer, oauth_verifier);

            final Editor edit = prefs.edit();
            edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
            edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
            edit.commit();

            String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
            String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

            consumer.setTokenWithSecret(token, secret);
            context.startActivity(new Intent(context,AndroidTwitterSample.class));

            executeAfterAccessTokenRetrieval();

            Log.i(TAG, "OAuth - Access Token Retrieved");

        } catch (Exception e) {
            Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
        }

        return null;
    }


    private void executeAfterAccessTokenRetrieval() {
        String msg = getIntent().getExtras().getString("tweet_msg");
        try {
            TwitterUtils.sendTweet(prefs, msg);
        } catch (Exception e) {
            Log.e(TAG, "OAuth - Error sending to Twitter", e);
        }
    }
}   

}

TwitterUtils:

public class TwitterUtils {

public static boolean isAuthenticated(SharedPreferences prefs) {

    String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
    String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

    AccessToken a = new AccessToken(token,secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);

    try {
        twitter.getAccountSettings();
        return true;
    } catch (TwitterException e) {
        return false;
    }
}

public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
    String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
    String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

    AccessToken a = new AccessToken(token,secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);
    twitter.updateStatus(msg);
}   
}

The problem is after 2 tweets, It is giving me an exception:

    W/System.err(5104): 403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (http://support.twitter.com/forums/10711/entries/15364).
    W/System.err(5104): error - Status is a duplicate.
    W/System.err(5104): request - /1/statuses/update.json
    W/System.err(5104): Relevant discussions can be on the Internet at:
     W/System.err(5104):    http://www.google.co.jp/search?q=15bb6564 or
     W/System.err(5104):    http://www.google.co.jp/search?q=010f3e5b
     W/System.err(5104): TwitterException{exceptionCode=[15bb6564-010f3e5b], statusCode=403, retryAfter=0, rateLimitStatus=null, version=2.1.11}
      W/System.err(5104):   at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:199)
      W/System.err(5104):   at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:75)
      W/System.err(5104):   at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:112)
      W/System.err(5104):   at twitter4j.Twitter.updateStatus(Twitter.java:593)
    W/System.err(5104):     at com.ecs.android.sample.twitter.TwitterUtils.sendTweet(TwitterUtils.java:38)
      W/System.err(5104):   at com.ecs.android.sample.twitter.AndroidTwitterSample$4.run(AndroidTwitterSample.java:84)

解决方案

From your error message:

error - Status is a duplicate.

It means that you cannot tweet the same message twice. If you have tweeted the message HI then you cannot tweet it again( at least on that day- not sure). You will get the Status is a duplicate error

这篇关于Twitter的集成:请求被理解,但它已被拒绝。这code是当请求被拒绝,由于更新的限制使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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