2012-04-04 100 views
5

我能夠使用twitter4j登錄到twitter並獲取登錄用戶的信息,但我無法從我的應用程序發佈推文。我正在使用java web應用程序發佈推文。看到我使用的下面的代碼。如何在java中使用twitter4j發佈推文?

String ACCESS_TOKEN = "ttttttttt"; 
    String ACCESS_TOKEN_SECRET = "gggggggggggggg"; 
    String CONSUMER_KEY = "gggggggggggg"; 
    String CONSUMER_SECRET = "hhhhhhhhhhhhh"; 
    String tweet = ""; 
    if (request.getParameter("tweet") != null) { 
     tweet = request.getParameter("tweet"); 
    } 
    AccessToken accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET); 
    OAuthAuthorization authorization = new OAuthAuthorization(ConfigurationContext.getInstance(), CONSUMER_KEY, CONSUMER_SECRET, accessToken); 
    Twitter twitter = new TwitterFactory().getInstance(authorization); 
    try { 
     //twitter.updateStatus("Hello World!"); 
     twitter.updateStatus(tweet); 
    } catch (TwitterException e) { 
     System.err.println("Error occurred while updating the status!"); 
    } 

我得到的follwing異常:

TwitterException {exceptionCode = [fa54b184-3bf2623f],的StatusCode = 401,retryAfter = 0,rateLimitStatus = NULL,版本2.1.5 =-SNAPSHOT(構建:d372a51b9b419cbd73d416474f4a855f3e889507 )}

請幫忙。

回答

7
  1. 轉到您已經創建的應用程序(https://dev.twitter.com)

  2. 檢查您的應用程序設置(>應用程序類型)

  3. '應用型'需要是讀取,寫入和訪問直接消息之一。如果不是,您可以輕鬆地進行更新。

(我測試你的代碼在處理環境,它是工作)

1

的StatusCode 401意味着你 not authorized

檢查您的憑證有效。如果他們是,也許你的應用程序尚未被用戶驗證。請參閱twitter4j site(點7)上的示例。

4

首先,重新生成您的訪問令牌/密鑰和使用者密鑰/密鑰。 然後試試這個。

String consumerKey = "yourconsumerKey "; 
     String consumerSecret = "yourconsumerSecret"; 
     String accessToken = "yourAccessToken"; 
     String accessSecret = "yourAccessSecret"; 

     ConfigurationBuilder cb = new ConfigurationBuilder(); 
     cb.setDebugEnabled(true) 
      .setOAuthConsumerKey(consumerKey) 
      .setOAuthConsumerSecret(consumerSecret) 
      .setOAuthAccessToken(accessToken) 
      .setOAuthAccessTokenSecret(accessSecret); 

     try 
     { 
      TwitterFactory factory = new TwitterFactory(cb.build()); 
      Twitter twitter = factory.getInstance(); 

      System.out.println(twitter.getScreenName()); 
      Status status = twitter.updateStatus(latestStatus); 
      System.out.println("Successfully updated the status to [" + status.getText() + "]."); 
      }catch (TwitterException te) { 
       te.printStackTrace(); 
       System.exit(-1); 
      }