2012-12-17 3 views
1

트위터의 스트리밍 API에서 트윗을 추출하는 간단한 자바 프로그램을 만들기 위해이 (http://cotdp.com/dl/TwitterConsumer.java) 코드 스 니펫을 OAuth 메소드로 수정했습니다. 결과는 아래 코드와 같습니다. 실행될 때 Connection Refused Exception을 발생시킵니다.Simple (Twitter + Streaming API + Java + OAuth) 예

나는 Twitter4J을 알고 있지만 다른 API에 가장 의존하지 않는 프로그램을 만들고 싶습니다.

나는 연구를 수행했으며 oauth.signpost 라이브러리는 Twitter의 스트리밍 API에 적합하다고 생각합니다. 나는 또한 나의 인증 세부 사항이 정확한지 확인했다. 내 트위터 액세스 수준은 '읽기 전용'입니다.

모든 안내에 감사드립니다. 이러한 유형의 문제가 이전에 답변되었지만 사과하지만, 예를 들어 Twitter4j에 의존하지 않고 스트리밍 API를 사용하는 방법을 보여주는 간단한 Java 예제를 찾을 수 없습니다.

감사

AHL

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 

import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import oauth.signpost.OAuthConsumer; 
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; 

/** 
* A hacky little class illustrating how to receive and store Twitter streams 
* for later analysis, requires Apache Commons HTTP Client 4+. Stores the data 
* in 64MB long JSON files. 
* 
* Usage: 
* 
* TwitterConsumer t = new TwitterConsumer("username", "password", 
*  "http://stream.twitter.com/1/statuses/sample.json", "sample"); 
* t.start(); 
*/ 
public class TwitterConsumer extends Thread { 
    // 
    static String STORAGE_DIR = "/tmp"; 
    static long BYTES_PER_FILE = 64 * 1024 * 1024; 
    // 
    public long Messages = 0; 
    public long Bytes = 0; 
    public long Timestamp = 0; 

    private String accessToken = ""; 
    private String accessSecret = ""; 
    private String consumerKey = ""; 
    private String consumerSecret = ""; 

    private String feedUrl; 
    private String filePrefix; 
    boolean isRunning = true; 
    File file = null; 
    FileWriter fw = null; 
    long bytesWritten = 0; 

    public static void main(String[] args) { 
     TwitterConsumer t = new TwitterConsumer(
      "XXX", 
      "XXX", 
      "XXX", 
      "XXX", 
      "http://stream.twitter.com/1/statuses/sample.json", "sample"); 
     t.start(); 
    } 

    public TwitterConsumer(String accessToken, String accessSecret, String consumerKey, String consumerSecret, String url, String prefix) { 
     this.accessToken = accessToken; 
     this.accessSecret = accessSecret; 
     this.consumerKey = consumerKey; 
     this.consumerSecret = consumerSecret; 
     feedUrl = url; 
     filePrefix = prefix; 
     Timestamp = System.currentTimeMillis(); 
    } 

    /** 
    * @throws IOException 
    */ 
    private void rotateFile() throws IOException { 
     // Handle the existing file 
     if (fw != null) 
      fw.close(); 
     // Create the next file 
     file = new File(STORAGE_DIR, filePrefix + "-" 
       + System.currentTimeMillis() + ".json"); 
     bytesWritten = 0; 
     fw = new FileWriter(file); 
     System.out.println("Writing to " + file.getAbsolutePath()); 
    } 

    /** 
    * @see java.lang.Thread#run() 
    */ 
    public void run() { 
     // Open the initial file 
     try { rotateFile(); } catch (IOException e) { e.printStackTrace(); return; } 
     // Run loop 
     while (isRunning) { 
      try { 

       OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); 
       consumer.setTokenWithSecret(accessToken, accessSecret); 
       HttpGet request = new HttpGet(feedUrl); 
       consumer.sign(request); 

       DefaultHttpClient client = new DefaultHttpClient(); 
       HttpResponse response = client.execute(request); 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(response.getEntity().getContent())); 
       while (true) { 
        String line = reader.readLine(); 
        if (line == null) 
         break; 
        if (line.length() > 0) { 
         if (bytesWritten + line.length() + 1 > BYTES_PER_FILE) 
          rotateFile(); 
         fw.write(line + "\n"); 
         bytesWritten += line.length() + 1; 
         Messages++; 
         Bytes += line.length() + 1; 
        } 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      System.out.println("Sleeping before reconnect..."); 
      try { Thread.sleep(15000); } catch (Exception e) { } 
     } 
    } 
} 
} 

답변

1

나는 코드를 시뮬레이션하기 위해 노력하고 오류가 매우 간단 것으로 나타났습니다. URL에 http 대신 https를 사용해야합니다.