2014-12-16 1 views
1

트위터 요청에 대한 내 소스 코드에 문제가 있습니다. 트위터에서 반환되는 응답은 빈 문자열입니다. 문제가 될 수있는 곳을 조언 해 줄 수 있습니까?트위터 전화 요청

dev.twitter.com에 내 앱을 등록했습니다. Reach Count라고 부릅니다.

이 코드는이 튜토리얼에서 가져온되어 http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/

package count_reach_twitter; 

//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.UnsupportedEncodingException; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLEncoder; 
import javax.net.ssl.HttpsURLConnection; 
import org.apache.commons.codec.binary.Base64; 
import org.json.JSONArray; 
import org.json.JSONObject; 

/** 
* 
* @author Martin 
*/ 
public class TwitterCall { 

    // Encodes the consumer key and secret to create the basic authorization key 
private static String encodeKeys(String consumerKey, String consumerSecret) { 
    try { 
     String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8"); 
     String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8"); 

     String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret; 
     byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes()); 

     return new String(encodedBytes); 
    } 
    catch (UnsupportedEncodingException e) { 
     return new String(); 
    } 
} 

// Writes a request to a connection 
private static boolean writeRequest(HttpsURLConnection connection, String textBody) { 
    try { 
     BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 
     wr.write(textBody); 
     wr.flush(); 
     wr.close(); 

     return true; 
    } 
    catch (IOException e) { return false; } 
} 


// Reads a response for a given connection and returns it as a string. 
private static String readResponse(HttpsURLConnection connection) { 
    try { 
     StringBuilder str = new StringBuilder(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     String line = ""; 
     while((line = br.readLine()) != null) { 
      str.append(line + System.getProperty("line.separator")); 
     } 
     return str.toString(); 
    } 
    catch (IOException e) { return new String(); } 
} 

// Constructs the request for requesting a bearer token and returns that token as a string 
private static String requestBearerToken(String endPointUrl) throws IOException { 
    HttpsURLConnection connection = null; 
    String encodedCredentials = encodeKeys("My customer key","My customer secret key"); 

    try { 
     URL url = new URL(endPointUrl); 
     connection = (HttpsURLConnection) url.openConnection();   
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Host", "api.twitter.com"); 
     connection.setRequestProperty("User-Agent", "Reach Count"); 
     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); 

     //writeRequest(connection, "grant_type=client_credentials"); 

     // Parse the JSON response into a JSON mapped object to fetch fields from. 
       System.out.println("Response: " + readResponse(connection)); 
       System.out.println("End"); 
     JSONObject obj = new JSONObject(readResponse(connection)); //(JSONObject)JSONValue.parse(readResponse(connection)); 
       //obj. 

     if (obj != null) { 
      String tokenType = (String)obj.get("token_type"); 
      String token = (String)obj.get("access_token"); 

      return ((tokenType.equals("bearer")) && (token != null)) ? token : ""; 
     } 
     return new String(); 
    } 
    catch (MalformedURLException e) { 
     throw new IOException("Invalid endpoint URL specified.", e); 
    } 
    finally { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 

// Fetches the first tweet from a given user's timeline 
public static String fetchTimelineTweet(String endPointUrl) throws IOException { 
    HttpsURLConnection connection = null; 

    try { 
     URL url = new URL(endPointUrl); 
     connection = (HttpsURLConnection) url.openConnection();   
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setRequestMethod("GET"); 
     connection.setRequestProperty("Host", "api.twitter.com"); 
     connection.setRequestProperty("User-Agent", "Reach Count"); 
     connection.setRequestProperty("Authorization", "Bearer " + requestBearerToken("https://api.twitter.com/oauth2/token")); 
     connection.setUseCaches(false); 


     // Parse the JSON response into a JSON mapped object to fetch fields from. 
     JSONArray obj = new JSONArray(readResponse(connection));//(JSONArray)JSONValue.parse(readResponse(connection)); 

     if (obj != null) { 
      String tweet = ((JSONObject)obj.get(0)).get("text").toString(); 

      return (tweet != null) ? tweet : ""; 
     } 
     return new String(); 
    } 
    catch (MalformedURLException e) { 
     throw new IOException("Invalid endpoint URL specified.", e); 
    } 
    finally { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 


} 

주요 기능은 다음 메소드를 호출한다 :

System.out.println(TwitterCall.fetchTimelineTweet("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Dj_Fedy&count=50")); 

당신에게

+0

빈 문자열을 반환하여 '예외'를 ​​잡는 몇 가지 장소가 있습니다. 어떤 시스템에 로깅을 추가 할 수 있습니까 (예 :'System.out.println ("Caught an Exception", e);) 어떤 일이 발생하는지 알아보십시오 – mthmulders

+0

java.io.IOException : 서버가 HTTP 응답 코드 : 403을 반환했습니다. URL은 https ://api.twitter.com/oauth2/token –

답변

0

감사 난 당신의 코드가를 얻는 이유는 확실하지 않다 403 트위터에서. 나는 두 가지를 생각할 수 있습니다 :

  1. Application-only authentication doc의 바닥에 따르면, 당신은 응용 프로그램 전용 인증을 지원하지 않는 엔드 포인트에 베어러 토큰을 사용할 때 403 응답이 주어진다. 응용 프로그램 전용 인증에서 GET on statuses/user_timeline이 허용되는지 여부를 확인할 수 없습니다.
  2. GET statuses/user_timeline doc에 따르면 사용자의 트윗은 인증 된 사용자가 타임 라인을 "소유"하거나 소유자의 승인 된 팔로어 일 때만 요청할 수 있습니다. 이것이 당신에게 필요한 것인지 확실하지 않습니다.
+0

예 : https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4.이 요청을 시도했습니다. . 같은 결과와 함께 –