我试图为访问令牌交换auth代码,但没有成功。我需要访问用户个人资料。 这是我的代码:
首先获取身份验证码:
编辑:
private void googleAuthenticate(){
try {
mOAauthHelper = new OAuthHelper("something.net", "xxxxx",
"https://www.googleapis.com/auth/userinfo.profile", "alex://myScheme");
String uri = mOAauthHelper.getRequestToken();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
//Intent i = new Intent(this, GoogleOAUTHActivity.class);
//i.putExtra(GoogleOAUTHActivity.GOOGLE_OAUTH_ENDPOINT_KEY, uri);
//startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
}
}
和
public OAuthHelper(String consumerKey, String consumerSecret, String scope,
String callbackUrl) throws UnsupportedEncodingException {
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
mProvider = new CommonsHttpOAuthProvider(
"https://www.google.com/accounts/OAuthGetRequestToken?scope="
+ URLEncoder.encode(scope, "utf-8"),
"https://www.google.com/accounts/OAuthGetAccessToken",
"https://www.google.com/accounts/OAuthAuthorizeToken?hd=default");
mProvider.setOAuth10a(true);
mCallbackUrl = (callbackUrl == null ? OAuth.OUT_OF_BAND : callbackUrl);
}
和
@Override
protected void onNewIntent(Intent intent) {
System.out.println("onNewIntent");
try {
Uri uri = intent.getData();
String oauthToken = uri.getQueryParameter("oauth_token");
// String oauthToken = uri.getQueryParameter("oauth_verifier");
System.out.println(oauthToken);
if(oauthToken != null){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("code", oauthToken));
pairs.add(new BasicNameValuePair("client_id", "something.net"));
pairs.add(new BasicNameValuePair("client_secret", "xxxxxx"));
pairs.add(new BasicNameValuePair("redirect_uri", "alex://myScheme"));
pairs.add(new BasicNameValuePair("grant_type", "authorization_code")); //Leave this line how it is
post.setEntity(new UrlEncodedFormEntity(pairs));
org.apache.http.HttpResponse response = client.execute(post);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody); // That just logs it into logCat
//authorizeGoogleSessionToServer(oauthToken);
}
} catch (Exception e) {
e.printStackTrace();
}
}
我得到: { “错误”:“invalid_request” }
有人知道如何解决这个问题吗?
感谢。
答案 0 :(得分:1)
你是双重编码 redirect_uri
参数。
应该看起来像::
pairs.add(new BasicNameValuePair("redirect_uri", "your_own_redirect_URI"));
此外,您应该小心不要混合协议的两种实现(OAuth1和OAuth2)。它们看起来一样但并不相同。