Запросить авторизацию информации о пользователе у Google (Gmail API) с помощью OkHttp - PullRequest
0 голосов
/ 05 ноября 2018

Я попробовал процесс авторизации из документации Google , но мне не удалось получить ответ от Google. Я попробовал OkHttp, и это не работает. Приложение вылетает после входа в систему с помощью Google-Sign-in. У меня уже есть crendatial.json, client_secret.json и токен аутентификации от Google Так как мне нужно отправить секретную информацию клиента в Google, мне интересно, отправил ли я ее в правильном формате?

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {

            // create Google sign-in account upon Google sign-in call
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            String idToken = account.getIdToken();
            String authCode = account.getServerAuthCode();
            // create user, save to database
            AddUserToDatabase(account);


            // post request to Google
    InputStream isClientSecret =      getResources().openRawResource(R.raw.client_secret);
            InputStreamReader isrClientSecret = new InputStreamReader(isClientSecret, Charset.forName("UTF-8"));
            Log.w("Before Response: ", "Lets GO!!");

            GoogleClientSecrets clientSecrets =
                    GoogleClientSecrets.load(
                            JacksonFactory.getDefaultInstance(), isrClientSecret);


            OkHttpClient client = new OkHttpClient();
            RequestBody body = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("client_id", clientSecrets.getDetails().getClientId())
                    .addFormDataPart("client_secret",clientSecrets.getDetails().getClientSecret())
                    .addFormDataPart("AuthCOde",authCode)
                    .addFormDataPart("RedirectURL","")
                    .build();

            Request request = new Request.Builder()
                    .url("https://www.googleapis.com/oauth2/v4/token")
                    .post(body)
                    .build();

            try {
                Response response = client.newCall(request).execute();

                Log.w("Response: ", response.body().toString());

            } catch (IOException e) {
                e.printStackTrace();
            }


            updateUI(account);

        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
            updateUI(null);
        } catch (FileNotFoundException e) {
            Log.w("File not found:::", "FNF");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

Это реализация из Документации Google.

            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),
                            authCode,
                            "").execute();
// redirect uri = "" because we don't have a back-end server.
...