簡體   English   中英

如何使用twitter API 1.1和java搜索推文

[英]How to search for tweets using twitter API 1.1 and java

Twitter API已從1.0更改為1.1。 現在,對於任何類型的查詢,都必須進行授權。 我正在使用java來獲取推文。 任何人都可以給我一些使用OAuth身份驗證獲取推文的java示例。

更新

使用twitter4j api是可能的。 http://twitter4j.org/en/ 下面給出一個例子

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);
    }

這里有問題

當我作為Java類運行時,此示例獨立工作。 但是當我在JSP中添加此代碼以便在webapp中進行測試時,它無法正常工作。 它向我顯示以下異常

    SEVERE: Servlet.service() for servlet [jsp] in context with path [/mypub] threw exception [java.lang.IllegalStateException: consumer key/secret pair already set.] with root cause
    java.lang.IllegalStateException: consumer key/secret pair already set.
        at twitter4j.TwitterBaseImpl.setOAuthConsumer(TwitterBaseImpl.java:264)
        at com.me.framework.tag.core.TweetFetch.doTag(TweetFetch.java:50)
        at org.apache.jsp.template.test_jsp._jspx_meth_wf_002dcore_005ftweetFetch_005f0(test_jsp.java:100)
        at org.apache.jsp.template.test_jsp._jspService(test_jsp.java:74)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)

問題是您正在多次設置使用者密鑰和令牌,如異常所示:

java.lang.IllegalStateException:已設置的使用者密鑰/秘密對。

之所以發生這種情況是因為TwitterFactory.getInstance()返回了Twitter的單例,然后每次向Servlet發出請求時都會調用setOAuthConsumersetOAuthAccessToken

您需要確保只配置一次Twitter實例,而不是每次請求時都配置。

實現這一目標的一種方法是通過使用TwitterFactory.getInstance(AccessToken)要求TwitterFactory為您提供經過身份驗證的Twitter實例:

final AccessToken accessToken = new AccessToken("Your-Access-Token", "Your-Access-Token-Secret");
final Twitter twitter = TwitterFactory.getInstance(token);
...

這種工廠方法的另一個好處是它可以為您返回一個緩存的,經過身份驗證的Twitter實例。

您可以使用codebird js庫進行推文搜索。 您只需要在Twitter上創建一個應用程序並記下以下內容:

  1. 消費者密鑰
  2. 消費者密鑰
  3. 訪問令牌
  4. 訪問令牌秘密

從GitHub的庫下載codebird JS庫在這里

用法:

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
);

我使用本教程使用帶有OAuth身份驗證的twitter api 1.1搜索推文

我已經修改了代碼以實現我的可用性而且它沒有使用twitter4j ,這在目前很好,因為OA 構建中沒有OAuth搜索(我在某處找不到該位置的地方)

還添加了獲取Twitter時間線

代碼在Groovy中

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       
}

TweetsInfo是一個包含String text, String fromUser, String expandedURL, String createdAt的Pojo類String text, String fromUser, String expandedURL, String createdAt (這是我的要求)

希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM