2016-03-07 2 views
0
public class TwitterStreamImpl implements TwitterStream { 

    public void setUpStream() throws InterruptedException { 
     final String consumerKey = getTwitterCredentials().get(0).toString(); 
     final String consumerSecret = getTwitterCredentials().get(1).toString(); 
     final String token = getTwitterCredentials().get(2).toString(); 
     final String secret = getTwitterCredentials().get(3).toString(); 

     BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); 
     StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint(); 
     // add some track terms 
     endpoint.trackTerms(Lists.newArrayList("twitterapi", "#yolo", "trump", "donald", "lol")); 

     Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret); 
     // Authentication auth = new BasicAuth(username, password); 

     // Create a new BasicClient. By default gzip is enabled. 
     BasicClient client = new ClientBuilder() 
       .hosts(Constants.STREAM_HOST) 
       .endpoint(endpoint) 
       .authentication(auth) 
       .processor(new StringDelimitedProcessor(queue)) 
       .build(); 

     // Establish a connection 
     client.connect(); 

     // Do whatever needs to be done with messages 
     for (int msgRead = 0; msgRead < 1000; msgRead++) { 
      if (client.isDone()) { 
      System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage()); 
      break; 
      } 

      String msg = queue.poll(5, TimeUnit.SECONDS); 
      if (msg == null) { 
      System.out.println("Did not receive a message in 5 seconds"); 
      } else { 
      System.out.println(msg); 
      } 
     } 

     client.stop(); 
    } 

    /** 
    * Reads twitterStup.txt from C:/Users/"user"/documents/ and returns them as 
    * an array 
    * 
    * @return Twitter Api Credentials 
    */ 
    private ArrayList getTwitterCredentials() { 
     BufferedReader in; 
     String str; 
     ArrayList<String> list = new ArrayList<String>(); 
     try { 
      in = new BufferedReader(new FileReader("*******")); 

      while ((str = in.readLine()) != null) { 
       list.add(str); 
      } 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return list; 
    } 

Журнал консоли говорит:Получить твиты из Twitter ЖСК API

Did not receive a message in 5 seconds 

И он говорит, что каждые пять секунд. Я хочу «sysout» (жить) каждый твит, у которого есть одна из конечных треков в нем. Но нет ошибки или чего-то подобного. Возможно, проблема с прокси-сервером?

ответ

1

Код работает, как и в то время. Проблема была прокси. Поскольку я был в офисной сети, подключение к потоку было невозможно. Поэтому я попробовал это с помощью своего собственного ноутбука, догадываюсь, что это сработало.

Смежные вопросы