如何获得包含授权码的 google 令牌响应?

How to get google Token response which includes authorization code?

我需要一种方法来获取 google 的响应,其中包括我从 Google 应用程序市场安装应用程序后的授权代码 或者有什么方法可以获取授权代码?

我用来检索访问令牌的代码

 String url = "https://www.googleapis.com/oauth2/v3/token";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "code=authorization code returned from previous request&client_id=my_client_id&client_secret=my_client_secret_from dev console&redirect_uri=google app oauth redirect uri&grant_type=authorization_code";
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
            wr.flush();

好的,这就是你的做法。

首先获取授权URL如下,

String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(
                GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId,
                nextUrl, GoogleResellerAdvController.SCOPES)
                .setAccessType("offline").build();

一旦调用此方法,您将获得授权码,该授权码将被传递以检索刷新令牌和访问令牌。 setAccessType("offline")授权时只有需要refresh token才需要,如果只需要access token可以忽略,但是access token会在一小时后过期。

令牌响应检索:

AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder(
                BearerToken.authorizationHeaderAccessMethod(),
                HTTP_TRANSPORT,
                JSON_FACTORY,
                new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL),
                new ClientParametersAuthentication(
                        clientId, clientSecret),
                        clientId,
                        GoogleOAuthConstants.AUTHORIZATION_SERVER_URL
                ).setScopes(SCOPES).build();



        TokenResponse response = codeFlow.newTokenRequest(authorizationCode)
                .setRedirectUri(redirectUri).setScopes(SCOPES).execute();

响应将同时包含访问令牌和刷新令牌!干杯!