2013-06-18 21 views
2

我想实现Twitter搜索API V1.1无记名代码返回HTTP 400错误的Twitter搜索API V1.1

请纠正我,如果我错了。 我执行下面提到步骤:

Step 1) Created an App in Twitter. 
So I got the TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRETCODE. 

Step 2) I encoded the concatenation of the above keys separated by ":" with the base UTF-8. 

Step3) Get the bearer token with the above generated code. 

Step4) Use the bearer code to get the Tweets on the relevance of a keyword. 

我被困在步骤3,

在那里我得到了响应,::

Server returned HTTP response code: 400 for URL: https://api.twitter.com/oauth2/token 
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) 
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source) 
    at com.tcs.crm.socialCRM.action.TwitterIntegration.requestBearerToken(TwitterIntegration.java:74) 
    at com.tcs.crm.socialCRM.action.TwitterIntegration.getStatusSearch(TwitterIntegration.java:27) 
    at com.tcs.crm.socialCRM.action.TwitterIntegration.main(TwitterIntegration.java:103) 

我的代码::

HttpsURLConnection connection = null; 
      PrintWriter outWriter = null; 
      BufferedReader serverResponse = null; 

      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", "Search Tweets"); 
       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); 
       connection.setDoOutput(true); 


       logger.info("Point 1"); 

       //CREATE A WRITER FOR OUTPUT 
       outWriter = new PrintWriter(connection.getOutputStream()); 

       logger.info("Point 2"); 

       //SEND PARAMETERS 
       outWriter.println("grant_type=client_credentials"); 
       outWriter.flush(); 
       outWriter.close(); 

       logger.info("Point 3"); 
       //RESPONSE STREAM 
       serverResponse = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

       JSONObject obj = (JSONObject)JSONValue.parse(serverResponse); 


       logger.info("The return string is "+obj.toString()); 
       return obj.toString(); 

请让我知道如何解决此问题。

回答

2

我与来自Twitter的不记名令牌有同样的问题。此外,我测试你的相同的代码,我收到了错误403.之后,我创建了我的自定义方法,以获取来自twitter的持票人令牌,我得到了解决方案。

HttpClient httpclient = new DefaultHttpClient(); 

    String consumer_key="YOUR_CONSUMER_KEY"; 
    String consumer_secret="YOUR_CONSUMER_SECRET"; 

    // Following the format of the RFC 1738 
    consumer_key=URLEncoder.encode(consumer_key, "UTF-8"); 
    consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8"); 

    String authorization_header_string=consumer_key+":"+consumer_secret;   
    byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes()); 


    String encodedString = new String(encoded); //converting byte to string 

    HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token"); 
    httppost.setHeader("Authorization","Basic " + encodedString); 

    List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 

    parameters.add(new BasicNameValuePair("grant_type", "client_credentials")); 

    httppost.setEntity(new UrlEncodedFormEntity(parameters)); 
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); 
    ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
    String responseBody = httpclient.execute(httppost, responseHandler); 

祝你好运!

1

Twitter的dev的文档告诉所带来的 “内容长度”:

https://dev.twitter.com/oauth/application-only

(参见 “实施例结果” 下面的 “步骤2:获取承载令牌”)

然而,在我的情况下(与PHP),它只适用于我删除“内容长度”

+0

+ 1 。将通过链接。谢了哥们 –

0

我知道这是比较晚的,但我发现,以下为我工作(感谢@jctd_BDyn的代码编码为基本身份验证的密钥和密码):所提供的参考

private String createBasicAuth() throws UnsupportedEncodingException { 
    String consumer_key="YOUR_CONSUMER_KEY"; 
    String consumer_secret="YOUR_CONSUMER_SECRET"; 

    // Following the format of the RFC 1738 
    consumer_key=URLEncoder.encode(consumer_key, "UTF-8"); 
    consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8"); 

    String authorization_header_string=consumer_key+":"+consumer_secret;   
    byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes()); 

    return new String(encoded); //converting byte to string 
} 

private HttpURLConnection createBearerTokenConnection() throws IOException { 
    URL url = new URL("https://api.twitter.com/oauth2/token"); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); 
    connection.setRequestProperty("Authorization", "Basic " + createBasicAuth()); 
    connection.setRequestMethod("POST"); 
    connection.setUseCaches(false); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    String formData = "grant_type=client_credentials"; 
    byte[] formDataInBytes = formData.getBytes("UTF-8"); 
    OutputStream os = connection.getOutputStream(); 
    os.write(formDataInBytes); 
    os.close(); 
    log.info("Sending 'POST' request to URL : " + bearerTokenUrl); 
    return connection; 
} 

public Optional<BearerToken> getBearerToken() { 
    try { 
     HttpURLConnection connection = createBearerTokenConnection(); 

     int responseCode = connection.getResponseCode(); 
     log.info("Response Code : " + responseCode); 

     BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     String inputLine; 
     StringBuffer response = new StringBuffer(); 
     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
     in.close(); 

     if (responseCode == 200) { 
      // Transforming from JSON string to POJO 
      return transformer.toBearerToken(response.toString()); 
     } else { 
      log.error("Unexpected response code with response " + response.toString()); 
     } 
    } catch (IOException e) { 
     log.error(String.format("IO exception on POST to %s", bearerTokenUrl), e); 
    } 
    return Optional.empty(); 
}