[英]twitter application only authentication java android with twitter4j
我正在尝试使用oauth2从twitter获取用户时间线(仅用于应用程序身份验证),但结果始终为null。 我没有OAUTH的经验,我已经看了几个教程和示例,但到目前为止没有运气。 我需要在不需要用户登录的情况下检索特定用户时间线(在此示例中为Twitter)。
我有一个使用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的示例代码或教程,那将不胜感激
经过漫长的一天寻找问题,我找到了一个解决方案。 我仍然不确定这对多个用户同时是否有效。 但是当我测试它时,我得到了我指定的用户的最后一条推文。
我删除了connecttwitter函数,并在我的asynctask的DoInBackground中声明了Twitter对象。 要获得Oauth2身份验证,您需要获取持有者令牌。 这是由你的消费者密钥和秘密(所以这个HAS设置在你的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");
我有很多问题,所以我想详细说明人们在上面的评论中提出要求。
有几种方法可以将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);
}
}
}
构建它之后,您将看到所有推文分批输出到您的控制台。 我希望这可以帮助某人,并提供一个简洁的解决方案来工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.