2013-06-18 103 views
9

我試圖從twitter與oauth2(僅適用於應用程序的身份驗證),但結果始終爲null的用戶時間線。我沒有使用OAUTH的經驗,我已經看過一些教程和示例,但目前還沒有運氣。 我需要檢索特定的用戶時間表(在此示例中爲Twitter),而無需用戶登錄。twitter應用程序唯一身份驗證java安卓與twitter4j

我有一個使用twitter API 1的應用程序,我嘗試使用oauth2將我現有的代碼調整到新的API 1.1進行應用程序認證。所以代碼應該工作,除了它不能從Twitter獲得任何回報。如果我確實得到了一個結果,那麼它應該再次工作。

與Twitter的連接是在asyncop下面的函數twitterconnect中進行的。

這裏是我的代碼:

public class TwitterActivity extends Activity { 

private ConfigurationBuilder builder; 

// twitter consumer key and secret 
static String TWITTER_CONSUMER_KEY = "**************"; 
static String TWITTER_CONSUMER_SECRET = "*************"; 

// twitter acces token and accestokensecret 
static String TWITTER_ACCES_TOKEN = "************"; 
static String TWITTER_ACCES_TOKEN_SECRET = "************"; 

ArrayList<Tweet> tweets = new ArrayList<Tweet>(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.twitter); 

    new AsyncOp().execute("test"); 

} 

//Async class... 
    public class AsyncOp extends AsyncTask<String, Void,List<twitter4j.Status>> { 

    protected List<twitter4j.Status> doInBackground(String... urls) { 

    //auth with twitter 
     List<twitter4j.Status> statuses = null; 
     try { 
      Twitter twitter=twitterConnect(); 

      statuses = twitter.getUserTimeline("Twitter"); 

      return statuses; 
     } catch (Exception ex) { 

      Log.d("Main.displayTimeline", "" + ex.getMessage()); 
     } 
     return statuses; 
    } 


    protected void onPostExecute(List<twitter4j.Status> statuses) { 

    try { 

    String TWITTER="EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf=new 
    SimpleDateFormat(TWITTER, Locale.ENGLISH); sf.setLenient(true); 

    for(int i=0;i<statuses.size();i++){ 

    twitter4j.Status stat = statuses.get(i); 
    User user=stat.getUser(); 
    Date datePosted=stat.getCreatedAt(); 
    String text=stat.getText(); 
    String name=user.getName(); 
    String profile_image_url=user.getProfileImageURL(); 
    Tweet t =new Tweet(datePosted,text,name,profile_image_url,twitterHumanFriendlyDate(datePosted)); 

    tweets.add(t); 
    // logcat info 
    Log.i("date",datePosted.toString()); 
    Log.i("text",text); 
    Log.i("user",name); 
    Log.i("userprofilepic",profile_image_url); 
    Log.i("timeofpost",twitterHumanFriendlyDate(datePosted)); 
    } 

    ListView listView = (ListView) findViewById(R.id.ListViewId); 
    listView.setAdapter(new UserItemAdapter(TwitterActivity.this, 
    R.layout.listitem, tweets)); 
    ProgressBar bar=(ProgressBar) findViewById(R.id.progressBar1); 
    bar.setVisibility(View.GONE); 
    } catch 
    (Exception e) { e.printStackTrace(); } } 

} 

public class UserItemAdapter extends ArrayAdapter<Tweet> { 
    private ArrayList<Tweet> tweets; 

    public UserItemAdapter(Context context, int textViewResourceId, 
      ArrayList<Tweet> tweets) { 
     super(context, textViewResourceId, tweets); 
     this.tweets = tweets; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View v = convertView; 
     if (v == null) { 
      LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      v = vi.inflate(R.layout.listitem, null); 
     } 

     Tweet tweet = tweets.get(position); 
     if (tweet != null) { 
      TextView username = (TextView) v.findViewById(R.id.username); 
      TextView message = (TextView) v.findViewById(R.id.message); 
      ImageView image = (ImageView) v.findViewById(R.id.avatar); 
      TextView date = (TextView) v.findViewById(R.id.date); 
      if (username != null) { 
       username.setText(tweet.username); 
      } 

      if (message != null) { 
       message.setText(tweet.message); 
      } 

      if (image != null) { 
       image.setImageBitmap(getBitmap(tweet.image_url)); 
      } 

      if (date != null) { 
       date.setText(tweet.hfdate); 

      } 
     } 
     return v; 
    } 
} 

public Bitmap getBitmap(String bitmapUrl) { 
    try { 
     URL url = new URL(bitmapUrl); 
     return BitmapFactory.decodeStream(url.openConnection() 
       .getInputStream()); 
    } catch (Exception ex) { 
     return null; 
    } 
} 


// build twitter 

public Twitter twitterConnect() throws Exception 
{ 

    // setup 
    builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY).setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); 
    OAuth2Token token = new TwitterFactory(builder.build()).getInstance().getOAuth2Token(); 


// exercise & verify 
    ConfigurationBuilder cb = new ConfigurationBuilder(); 
    cb.setUseSSL(true); 
    cb.setApplicationOnlyAuthEnabled(true); 

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

    twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET); 
    twitter.setOAuth2Token(token); 

    return twitter; 
} 

public String twitterHumanFriendlyDate(Date dateCreated) { 
    // parse Twitter date 
    SimpleDateFormat dateFormat = new SimpleDateFormat(
      "EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH); 
    dateFormat.setLenient(false); 
    Date created = dateCreated; 

    // today 
    Date today = new Date(); 

    // how much time since (ms) 
    Long duration = today.getTime() - created.getTime(); 

    long second = 1000; 
    long minute = second * 60; 
    long hour = minute * 60; 
    long day = hour * 24; 

    if (duration < second * 7) { 
     return "right now"; 
    } 

    if (duration < minute) { 
     int n = (int) Math.floor(duration/second); 
     return n + " seconds ago"; 
    } 

    if (duration < minute * 2) { 
     return "about 1 minute ago"; 
    } 

    if (duration < hour) { 
     int n = (int) Math.floor(duration/minute); 
     return n + " minutes ago"; 
    } 

    if (duration < hour * 2) { 
     return "about 1 hour ago"; 
    } 

    if (duration < day) { 
     int n = (int) Math.floor(duration/hour); 
     return n + " hours ago"; 
    } 
    if (duration > day && duration < day * 2) { 
     return "yesterday"; 
    } 

    if (duration < day * 365) { 
     int n = (int) Math.floor(duration/day); 
     return n + " days ago"; 
    } else { 
     return "over a year ago"; 
    } 
} 

}

是我的問題機智的OAuth的方法?或者可能會用getusertimeline? 如果任何人有與twitter4j oauth2一些示例代碼或教程,不勝感激

回答

11

經過漫長的一天搜索問題,我找到了一個解決方案。我仍然不確定這會同時適用於多個用戶。但是當我測試它時,我從我指定的用戶那裏得到最後一條推文。

我刪除了connecttwitter函數,並在我的asynctask的DoInBackground中聲明瞭Twitter對象。要獲得Oauth2身份驗證,您需要獲取不記名令牌。這是從您的使用者密鑰和機密(所以這也被你的Twitter對象上設置)這裏是改變的代碼(從我的connecttwitter到doinbackground異步任務的代碼)與一些修改

ConfigurationBuilder builder=new ConfigurationBuilder(); 
      builder.setUseSSL(true); 
      builder.setApplicationOnlyAuthEnabled(true); 

      // setup 
      Twitter twitter = new TwitterFactory(builder.build()).getInstance(); 

      // exercise & verify 
      twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET); 
      // OAuth2Token token = twitter.getOAuth2Token(); 
      twitter.getOAuth2Token(); 
    statuses = twitter.getUserTimeline("Twitter"); 
+0

你好,你可以給我完整的工作代碼「抓取twitter feed」嗎?我遇到問題 –

+0

'方法setApplicationOnlyAuthEnabled(boolean)未定義類型ConfigurationBuilder' – jul

+1

@jul下載並從這裏添加最新的Twitter4J庫快照[http://twitter4j.org/en/index.html#snapshot](http ://twitter4j.org/en/index.html#snapshot) – Mani

3

我有這個問題很多,所以想我會詳細闡述,因爲人們在上面的評論請求。

有幾種方法可以將Twitter4j的相應設置加載爲僅作爲應用程序運行。根據這裏的文檔(http://twitter4j.org/en/configuration.html),我去了一個屬性文件。

步驟如下:

1)創建的確切twitter4j.properties文件名,在您的項目根屬性文件。如果是我,我會把這個放在/resources導演裏面,但不管。

2)twitter4j.properties文件中把這樣的事情:

debug=true 
enableApplicationOnlyAuth=true 
http.useSSL=true 
oauth.consumerKey=[consumer key here] 
oauth.consumerSecret=[consumer secret here] 

注:SSL和enableApplicationOnlyAuth是非常重要的!如果你還沒有得到消費者的鍵/祕密又那麼你可以按照指南的其他地方,但你通過這裏註冊您的應用(https://apps.twitter.com/

3)下載twitter4j獲取並在項目中包含的jar - http://twitter4j.org/en/index.html#howToUse

4)這是一個完整的解決方案 - 請注意,這需要一個搜索參數,如#Toyota。或者你可以硬編碼 - Query query = new Query("#Toyota");

package twittertest; 

import java.io.IOException; 
import java.util.List; 
import twitter4j.Query; 
import twitter4j.QueryResult; 
import twitter4j.Status; 
import twitter4j.Twitter; 
import twitter4j.TwitterException; 
import twitter4j.TwitterFactory; 
import twitter4j.auth.OAuth2Token; 

/** 
* 
* @author That Guy 
*/ 
public class TwitterTest { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws IOException, TwitterException { 
     if (args.length < 1) { 
      System.out.println("java twitter4j.examples.search.SearchTweets [query]"); 
      System.exit(-1); 
     } 

     Twitter twitter = new TwitterFactory().getInstance(); 
     twitter.getOAuth2Token(); 

     try { 
      Query query = new Query(args[0]); 
      QueryResult result; 
      do { 
       result = twitter.search(query); 
       List<Status> tweets = result.getTweets(); 
       for (Status tweet : tweets) { 
        System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); 
       } 
      } while ((query = result.nextQuery()) != null); 
      System.exit(0); 
     } catch (TwitterException te) { 
      te.printStackTrace(); 
      System.out.println("Failed to search tweets: " + te.getMessage()); 
      System.exit(-1); 
     } 
    } 

} 

你蓋了之後,你會看到所有的鳴叫分批輸出到您的控制檯。我希望能幫助別人,並提供一個簡潔的解決方案,從

相關問題