使用OAuth搜索Twitter

时间:2012-10-09 14:51:47

标签: java twitter oauth access-token

好的,所以每次运行我的程序时都会获得Twitter的访问令牌...(目前这很繁琐,但我会发现如何让它成为持久存储)...我该如何使用这个访问令牌,以便在我搜索时,我不会得到

  

“超出了限额。客户每小时的请求数不得超过150个。”    错误?

当我搜索以下内容时会发生这种情况:“https://api.twitter.com/1/users/show.json?screen_name=[screenName]” 编码为:

BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));

在我的代码中:

public class UDC  {
private static String term1;
private static String term2;
public static String PIN;

private static final String twitterSearch = "http://search.twitter.com/search.json?q=%23";
private static String rppPage = "&rpp=500&page=1";

private static final String ffGet = "https://api.twitter.com/1/users/show.json?screen_name=";
private static final String CONSUMER_KEY = "K7el7Fqu7UtcJv3A3ssOQ";
private static final String CONSUMER_SECRET = "w7ZX27ys58mafLYeivuA2POVe0gjhTIIUH26f2IM";

private static String entities = "&include_entities=true";

static Object[][] tableData = new Object[500][6];
static SearchResultC s = new SearchResultC();
static StringBuffer buff = new StringBuffer();
static StringBuffer buff1 = new StringBuffer();

public static void main (String args[]) throws Exception{
    verifyURL v = new verifyURL();
    Twitter twitter = new TwitterFactory().getInstance();
      twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
      RequestToken requestToken = twitter.getOAuthRequestToken();
      AccessToken accessToken = null; // = loadAccessToken(Integer.parseInt(args[0]));
            //Twitter twitter = factory.getInstance);
            //twitter.setOAuthConsumerKey(COMSUMER_KEY, COMSUMER_SECRET);
            //twitter.setOAuthAccessToken(accessToken);

      v.valURLText.setText(requestToken.getAuthorizationURL());
      v.vFrame.setVisible(true);
      int p = 0;

      do {
          //nothing
      } while (v.vFrame.isVisible());
                try {
                  if (PIN.length() > 0) {
                      accessToken = twitter.getOAuthAccessToken(requestToken, PIN);
                  } else {
                      accessToken = twitter.getOAuthAccessToken();
                  }
              } catch (TwitterException te) {
                  if(401 == te.getStatusCode()) {
                      showErrorPane("Unable to get access code", "Error");
                      p = 1;
                  } else {
                      te.printStackTrace();
                  }
              }

      //storeAccessToken(twitter.verifyCredentials().getId(), accessToken);


    if (p == 0) {
        initComponents();
        UDTFrame.setVisible(true);
    } else {
        System.exit(0);
    }
}


@SuppressWarnings({ "static-access"})
private static void searchButtonMouseClicked(String t1, String t2) throws IOException {

    if(t1.equals("") || t2.equals("") || t1.equals(t2))
        {
        showErrorPane("Invalid Search Terms", "Search Error");
    }

    else 
    {
        s.getInitComponents();
        clicked(t1, 0);
        clicked(t2, 3);
        s.SRTFrame.setVisible(true);
        s.sTerm1Field.setText(t1);
        s.sTerm2Field.setText(t2);
    }
}

@SuppressWarnings("static-access")
public static void clicked(String term, int t){
    UDTFrame.setVisible(false);
    float follower;
    float friends;
    float ffRatio;
    float DUA;
    int statuses;
    int day;
    int year;
    String month;

    try {
        URL searchURL1 = new URL (twitterSearch + term + rppPage);
        //String searchURL = new String (twitterSearch + term + rppPage);
        BufferedReader br = new BufferedReader( new InputStreamReader(searchURL1.openConnection().getInputStream()));

        //OAuthRequest request = new OAuthRequest(Verb.POST, searchURL);

        int c;
        while ((c=br.read()) != -1) {
            buff.append((char)c);
        }
        br.close();

        /*******************************************************************************************/
        /*******************************************************************************************/
        /******************************** follower/friend ratio ************************************/
        /*******************************************************************************************/
        /*******************************************************************************************/
        JSONObject js = new JSONObject(buff.toString());
        JSONArray tweets = js.getJSONArray("results");
        JSONObject tweet = new JSONObject();
        for(int i=0; i < tweets.length(); i++) {
            tweet = tweets.getJSONObject(i);
            //System.out.println(tweet);
            //user[i] = tweet.getString("from_user_name");
            //System.out.println(tweet.getString("from_user_name"));
            //System.out.println(user[i]);
            String userName = tweet.getString("from_user");

            //URL ffUser = new URL(ffGet + user[i] + entities);
            URL ffUser = new URL(ffGet + userName + entities);
            String ffUser1 = new String(ffGet + userName + entities);

            BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
            OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);

            int d, e = 0;
            while((d = ff.read()) != -1) {
                buff1.append((char)d);
                e++;
            }
            ff.close();

            JSONObject js1 = new JSONObject(buff1.toString());
            //System.out.println(js1);
            //JSONArray userData = new JSONArray(buff1.toString());
            //JSONObject userData1;
            //for(int j = 0; j < js1.length(); i++){
                //userData1 = userData.getJSONObject(j);
                follower =  js1.getInt("followers_count");
                friends = js1.getInt("friends_count");
                ffRatio = friends/follower;

                String createdDate = js1.getString("created_at");
                statuses = js1.getInt("statuses_count");

                String nameData = js1.getString("name");
                String gen = gender(nameData);


        //}

    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}

我对这个OAuth和访问令牌都是全新的,所以任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用

OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);

您正在使用Scribe库执行未经身份验证的请求(您从未实例化OAuthService对象,该对象必须用于sign此请求。所以当你这么做时,Twitter就会拒绝这些请求。

所以你的问题确实来自混合Twitter4J和Scribe。