2

我正在尝试实现 Twitter Search 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();

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

4

3 回答 3

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);

祝你好运!

于 2013-07-02T11:19:46.270 回答
1

Twitter 开发文档告诉提供“内容长度”:

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

(参见“步骤 2:获取不记名令牌”下面的“示例结果”)

但是,在我的情况下(使用 PHP),它只有在我删除 "Content-Length" 时才有效

于 2014-11-20T10:49:56.820 回答
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();
}
于 2016-12-27T15:09:34.517 回答