2012-09-28 95 views
2

在oauth2 dance的第1步之後,我可以在重定向URL中檢索代碼。這工作正常。但隨後,Stocktwits API - AuthorizationCodeGrant HttpResponseException:400 Bad Request

我有一個 'com.google.api.client.http.HttpResponseException:400錯誤的請求' 的錯誤

試圖讓accessTokenResponse。任何想法爲什麼?

AuthorizationCodeGrant request = new AuthorizationCodeGrant(new NetHttpTransport(), 
           new JacksonFactory(), 
           OAuth2ClientCredentials.ACCESS_TOKEN_URL, 
           OAuth2ClientCredentials.CLIENT_ID, 
           OAuth2ClientCredentials.CLIENT_SECRET, 
           code, 
           OAuth2ClientCredentials.REDIRECT_URI); 

         try { 
          AccessTokenResponse accessTokenResponse = request.execute(); 
          CredentialStore credentialStore = new SharedPreferencesCredentialStore(prefs); 
          credentialStore.write(accessTokenResponse); 
         } catch (IOException e) { 
          Log.e(TAG, "error= "+e); 
          e.printStackTrace(); 
         } 

這是觸發錯誤的行:

AccessTokenResponse accessTokenResponse = request.execute(); 

我使用 'com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.AuthorizationCodeGrant'

我應該使用別人嗎?任何建議?

+0

您可以嘗試手動請求授權令牌並返回代碼並查看是否有效。有關示例,請參閱http://stocktwits.com/developers/docs/api#oauth-token-docs。 – AdamB

回答

1

請參閱authorization flowoauth/token end-point的第5步。

好像你缺少了grant_type。

+0

然後我不能使用AuthorizationCodeGrant(因爲它不需要TOKEN_GRANT_TYPE)。你會建議使用什麼呢?我想知道你是否對外部圖書館有任何偏好? – Hubert

+0

您可以嘗試手動或通過命令行上的curl來獲取access_token,或者甚至在客戶端執行操作(如果其他所有操作都失敗)。 –

1

這看起來是工作:

// Create a new HttpClient and Post Header 
         HttpClient httpclient = new DefaultHttpClient(); 
         HttpPost httppost = new HttpPost(OAuth2ClientCredentials.ACCESS_TOKEN_URL); 

         try { 
          // Add your data 
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5); 
          nameValuePairs.add(new BasicNameValuePair("client_id", OAuth2ClientCredentials.CLIENT_ID)); 
          nameValuePairs.add(new BasicNameValuePair("client_secret", OAuth2ClientCredentials.CLIENT_SECRET)); 
          nameValuePairs.add(new BasicNameValuePair("code", code)); 
          nameValuePairs.add(new BasicNameValuePair("grant_type", OAuth2ClientCredentials.TOKEN_GRANT_TYPE)); 
          nameValuePairs.add(new BasicNameValuePair("redirect_uri", OAuth2ClientCredentials.REDIRECT_URI)); 
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

          Log.i(TAG, "httppost= "+inputStreamToString(httppost.getEntity().getContent())); 

          // Execute HTTP Post Request 
          HttpResponse response = httpclient.execute(httppost); 
          Log.i(TAG, "response= "+inputStreamToString(response.getEntity().getContent())); 

         } catch (ClientProtocolException e) { 
          Log.e(TAG, "error= "+e); 
         } catch (IOException e) { 
          Log.e(TAG, "error= "+e); 
         } 

重定向URL包含訪問令牌,我需要。

+0

很高興你知道了,一旦你有grant_type在那裏工作。 –