以前写的一段,看看还能不能用吧,登录Google Drive用的,配合WebView和AsyncHttpClient用。
public class GoogleDriveLoginActivity extends WebAuthActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); @SuppressWarnings("deprecation")
String url = String.format(
"https://accounts.google.com/o/oauth2/auth?redirect_uri=%s&client_id=%s&scope=%s&%s",
URLEncoder.encode(GoogleDrivePlatform.REDIRECT_URI), // Redirect URI
URLEncoder.encode(GoogleDrivePlatform.CLIENT_ID), // Client Id
URLEncoder.encode(GoogleDrivePlatform.SCOPE), // Scope
"response_type=code&display=touch&access_type=offline");// Options
loadUrl(url);
} @Override
protected void onRedirect(String callbackUrl) {
super.onRedirect(callbackUrl);
Uri uri = Uri.parse(callbackUrl);
String code = uri == null ? null : uri.getQueryParameter("code");
if (code == null) {
App.logError("fail to handle callback: " + callbackUrl);
return;
}
// Get access token from code
RequestParams p = new RequestParams();
p.put("code", code);
p.put("grant_type", "authorization_code");
p.put("redirect_uri", GoogleDrivePlatform.REDIRECT_URI);
p.put("client_id", GoogleDrivePlatform.CLIENT_ID);
p.put("client_secret", GoogleDrivePlatform.SECRET);
App.getHttp().post("https://accounts.google.com/o/oauth2/token", p, new OnRequestActionHandler() { @Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
try {
new GoogleDrivePlatform(getApplicationContext()).save(response);
App.info(R.string.signed_in_to_google_drive);
setResult(RESULT_OK);
finish();
} catch (JSONException e) {
App.logError("fail to parse token JSON", e);
}
} @Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
App.logError("fail to access token: " + errorResponse.optString("error_description", null), throwable);
App.alert(R.string.fail_to_sign_in_to_google_drive);
}
});
}
}