【问题标题】:Bearer Code returning HTTP 400 error for Twitter Search API V1.1承载代码返回 Twitter 搜索 API V1.1 的 HTTP 400 错误
【发布时间】:2013-06-14 17:52:42
【问题描述】:

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

请告诉我如何解决此问题。

【问题讨论】:

    标签: java twitter oauth-2.0


    【解决方案1】:

    我在使用 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);
    

    祝你好运!

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

      • + 1 用于提供的参考。将通过链接。谢谢老哥
      【解决方案3】:

      我知道这已经很晚了,但我发现以下内容对我有用(感谢@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();
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 2012-09-14
        • 2013-08-15
        • 1970-01-01
        • 2013-06-10
        • 2013-07-24
        • 2013-08-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多