如何使用twitter API 1.1和java搜索推文
Twitter API已从1.0更改为1.1。现在,对于任何类型的查询,它都必须经过授权。我正在使用java获取推文。有谁能给我一些使用OAuth身份验证获取tweet的java示例吗 更新 使用twitter4j api是可能的。下面给出了一个例子如何使用twitter API 1.1和java搜索推文,java,twitter,twitter4j,Java,Twitter,Twitter4j,Twitter API已从1.0更改为1.1。现在,对于任何类型的查询,它都必须经过授权。我正在使用java获取推文。有谁能给我一些使用OAuth身份验证获取tweet的java示例吗 更新 使用twitter4j api是可能的。下面给出了一个例子 Twitter twitter = new TwitterFactory().getInstance(); AccessToken accessToken = new AccessToken("Your-Access-Token", "Y
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken("Your-Access-Token", "Your-Access-Token-Secret");
twitter.setOAuthConsumer("Consumer-Key", "Consumer-Key-Secret");
twitter.setOAuthAccessToken(accessToken);
try {
Query query = new Query("#IPL");
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
您可以使用codebird js库进行推特搜索。您只需在Twitter上创建一个应用程序,并记下以下内容:
var cb = new Codebird;
cb.setConsumerKey('YOURKEY', 'YOURSECRET');
cb.setToken('YOURTOKEN', 'YOURTOKENSECRET');
cb.__call(
'oauth2_token',
{},
function (reply) {
var bearer_token = reply.access_token;
}
);
cb.__call(
'search_tweets',
{
q : "your query which you want to search",
from : twitter_user
},
function (data)
{
console.log(data);
},
true // this parameter required
);
问题是您多次设置使用者机密和令牌,如异常所示: java.lang.IllegalStateException:已设置使用者密钥/密钥对 这是因为它返回了一个单一的
Twitter
,然后每次向Servlet发出请求时都会调用setOAuthConsumer
和setOAuthAccessToken
您需要确保只配置一次Twitter
实例,而不是每次发出请求时
实现这一点的一种方法是要求TwitterFactory
通过以下方式为您提供一个经过身份验证的Twitter
实例:
此工厂方法的另一个好处是,它可以为您返回一个缓存的、经过身份验证的Twitter
实例。我曾经使用带有OAuth身份验证的Twitter api 1.1搜索推文
我已经修改了代码以提高可用性,但它没有使用,这在目前是很好的,因为OAuth搜索在中不可用(我在某个地方读到它,目前找不到位置)
还添加了获取twitter时间线
密码在里面
TweetsHelper-TweetsHelper=new-TweetsHelper()
def bearerToken=tweetsHelper.requestBearerToken(TWITTER\u AUTH\u URL)
列表tweets=tweetsHelper.fetchTimeLineWeet(BealerToken)
私有最终def TWITTER_HOST=“api.TWITTER.com”
私有最终定义TWITTER_AUTH_URL=”https://api.twitter.com/oauth2/token"
私有最终def TWITTER_URL=”https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=INFAsupport&count=200"
私有HttpsURLConnection getHTTPSConnection(字符串方法,字符串端点URL){
HttpsURLConnection连接=空
URL URL=新URL(端点URL)
连接=(HttpsURLConnection)url.openConnection()
connection.setDoOutput(真)
connection.setDoInput(true)
connection.setRequestMethod(方法)
connection.setRequestProperty(“主机”,TWITTER\u主机)
setRequestProperty(“用户代理”,TWITTER\u句柄)
connection.setUseCaches(false)
回路连接
}
//获取BealerToken以获取推文
公共字符串requestBealerToken(字符串端点URL)引发IOException{
字符串encodedCredentials=encodeKeys()
HttpsURLConnection连接=空
试一试{
连接=getHTTPSConnection(“POST”,端点URL)
connection.setRequestProperty(“授权”、“基本”+encodedCredentials)
connection.setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=UTF-8”)
connection.setRequestProperty(“内容长度”,“29”)
connection.setUseCaches(false)
}
捕获(格式错误){
抛出新IOException(“指定的端点URL无效。”,e)
}
最后{
if(连接!=null){
连接断开()
}
}
writeRequest(连接,“授予类型=客户端凭据”)
JsonSlurper js=新的JsonSlurper()
def result=js.parseText(readResponse(连接))
字符串标记类型=结果?.token\u类型
字符串令牌=结果?.access\u令牌
返回((tokenType.equals(“bearer”)&((token!=null))?token:“
}
//搜索推文
公共列表fetchQueriedTweets(def BealerToken)引发IOException{
HttpsURLConnection连接=空
def dataCleanser=新的dataCleanser()
试一试{
connection=getHTTPSConnection(“GET”,TWITTER\uURL)
connection.setRequestProperty(“授权”、“承载人”+bearerToken)
}
捕获(格式错误){
抛出新IOException(“指定的端点URL无效。”,e)
}
最后{
if(连接!=null){
连接断开()
}
}
List tweets=new ArrayList()
试一试{
JSONObject obj=(JSONObject)JSONValue.parse(readResponse(connection))
JSONArray objArray=(JSONArray)obj.get(TWEET_状态)
if(objArray!=null){
对于(int i=0;i
字符串文本=tweet?.text
字符串createdAt=DateUtils.convertToUTC(parseTweetDate(tweet?.created_at))
字符串fromUser=tweet?.user?.name
字符串expandedURL=tweet?.entities?.url[0]?.expanded_url
if(有效周数(创建日期)){
TweetsInfo tweetinfo=新的TweetsInfo(文本、fromUser、expandedURL、createdAt)
推送(推送信息)
}
}
}
捕获(例外e){
log.info“TweetsHelper$e中的异常”
}
返回推文
}
TweetsInfo
是一个Pojo类,包含String text、String fromUser、String expandedURL、String createdAt
(这是我的要求)
希望这有帮助:)我昨天刚做了同样的事情,但使用了C。对于java,有一个名为twitter4j的库。这可能会有帮助。谢谢你的回答。但是我想要java的。客户端的问题是,我的代币对每个人都可见。谢谢。我会尝试让您知道。谢谢。我会尽力让你知道的。
var cb = new Codebird;
cb.setConsumerKey('YOURKEY', 'YOURSECRET');
cb.setToken('YOURTOKEN', 'YOURTOKENSECRET');
cb.__call(
'oauth2_token',
{},
function (reply) {
var bearer_token = reply.access_token;
}
);
cb.__call(
'search_tweets',
{
q : "your query which you want to search",
from : twitter_user
},
function (data)
{
console.log(data);
},
true // this parameter required
);
final AccessToken accessToken = new AccessToken("Your-Access-Token", "Your-Access-Token-Secret");
final Twitter twitter = TwitterFactory.getInstance(token);
...
TweetsHelper tweetsHelper = new TweetsHelper()
def bearerToken=tweetsHelper.requestBearerToken(TWITTER_AUTH_URL)
List<TweetsInfo> tweets=tweetsHelper.fetchTimelineTweet(bearerToken)
private final def TWITTER_HOST = "api.twitter.com"
private final def TWITTER_AUTH_URL = "https://api.twitter.com/oauth2/token"
private final def TWITTER_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=INFAsupport&count=200"
private HttpsURLConnection getHTTPSConnection(String method,String endpointUrl){
HttpsURLConnection connection = null
URL url = new URL(endpointUrl)
connection = (HttpsURLConnection) url.openConnection()
connection.setDoOutput(true)
connection.setDoInput(true)
connection.setRequestMethod(method)
connection.setRequestProperty("Host", TWITTER_HOST)
connection.setRequestProperty("User-Agent", TWITTER_HANDLE)
connection.setUseCaches(false)
return connection
}
//Fetch Bearertoken for getting tweets
public String requestBearerToken(String endPointUrl) throws IOException {
String encodedCredentials = encodeKeys()
HttpsURLConnection connection = null
try {
connection = getHTTPSConnection("POST",endPointUrl)
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials)
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
connection.setRequestProperty("Content-Length", "29")
connection.setUseCaches(false)
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e)
}
finally {
if (connection != null) {
connection.disconnect()
}
}
writeRequest(connection, "grant_type=client_credentials")
JsonSlurper js=new JsonSlurper()
def result=js.parseText(readResponse(connection))
String tokenType = result?.token_type
String token = result?.access_token
return ((tokenType.equals("bearer")) && (token != null)) ? token : ""
}
//Search tweets
public List<TweetsInfo> fetchQueriedTweets(def bearerToken) throws IOException {
HttpsURLConnection connection = null
def dataCleanser = new DataCleanser()
try {
connection = getHTTPSConnection("GET",TWITTER_URL)
connection.setRequestProperty("Authorization", "Bearer " + bearerToken)
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e)
}
finally {
if (connection != null) {
connection.disconnect()
}
}
List<TweetsInfo> tweets= new ArrayList<TweetsInfo>()
try{
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection))
JSONArray objArray = (JSONArray)obj.get(TWEET_STATUSES)
if (objArray != null) {
for(int i=0;i<objArray.length();i++){
String text = dataCleanser.escapeQuotes(((JSONObject)objArray.get(i)).get(TWEET_TEXT).toString())
String createdAt = DateUtils.convertToUTC(parseTweetDate(((JSONObject)objArray.get(i)).get(TWEET_CREATED_AT).toString()))
String fromUser = ((JSONObject)objArray.get(i)).get(TWEET_USER).get(TWEET_NAME).toString()
String expandedURL = ((JSONObject)objArray.get(i)).get(TWEET_ENTITIES).get(TWEET_URLS).get(0).get(TWEET_EXPANDED_URL).toString()
TweetsInfo tweet=new TweetsInfo(text,fromUser,expandedURL,createdAt)
tweets.push(tweet)
}
}
}
catch(Exception e){
log.info "Exception in TweetsHelper $e"
}
return tweets
}
//Fetch Twitter timeline
public List<TweetsInfo> fetchTimelineTweet(def bearerToken) throws IOException {
HttpsURLConnection connection = null
List<TweetsInfo> tweets= new ArrayList<TweetsInfo>()
def dataCleanser = new DataCleanser()
try {
connection = getHTTPSConnection("GET",TWITTER_URL)
connection.setRequestProperty("Authorization", "Bearer " + bearerToken)
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e)
}
finally {
if (connection != null) {
connection.disconnect()
}
}
JsonSlurper js=new JsonSlurper()
try{
def result=js.parseText(readResponse(connection))
result?.each{tweet->
String text = tweet?.text
String createdAt = DateUtils.convertToUTC(parseTweetDate(tweet?.created_at))
String fromUser = tweet?.user?.name
String expandedURL = tweet?.entities?.urls[0]?.expanded_url
if(validTweetForAWeek(createdAt)){
TweetsInfo tweetinfo=new TweetsInfo(text,fromUser,expandedURL,createdAt)
tweets.push(tweetinfo)
}
}
}
catch(Exception e){
log.info "Exception in TweetsHelper $e"
}
return tweets
}