Android Google People API错误:TokenResponseException:缺少参数:代码 [英] Android Google People API error: TokenResponseException: Missing parameter: code

查看:320
本文介绍了Android Google People API错误:TokenResponseException:缺少参数:代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用完了我的路。我遵循





Google Sign In class:

  public void Google_signIn(){

//迁移到人api
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// serverC lientId是一个OAuth 2.0 Web客户端ID
.requestServerAuthCode(Constants.Google_Client_ID)
.requestEmail()
.requestScopes(新范围(Scopes.PLUS_LOGIN),
新范围(PeopleScopes .USERINFO_EMAIL))
.build();

if(mGoogleApiClient == null){

mGoogleApiClient = new GoogleApiClient.Builder(activity)
.enableAutoManage(activity / * FragmentActivity * /,this / * OnConnectionFailedListener * /)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.addApi(LocationServices.API)
。建立();
}

意图signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
activity.startActivityForResult(signInIntent,GOOGLE_SIGN_IN);

成功登录后的处理程序结果:

  GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
if(result.isSuccess()){
new PeoplesAsync()。execute(result);

PeoplesAsync:

<$ PeoplesAsync扩展AsyncTask< GoogleSignInResult,Void,String> p $ p> {

@Override
保护无效onPreExecute(){
super.onPreExecute();

$ b @Override
保护字符串doInBackground(GoogleSignInResult ... params){

GoogleSignInAccount acct = params [0] .getSignInAccount();
JSONObject userInfo = new JSONObject();

尝试{

//基本概要信息
字符串G_id = acct.getId();
String G_email = acct.getEmail();
String G_name = acct.getDisplayName();
String G_url = acct.getPhotoUrl()。toString(); // profile img

userInfo.put(AccountCenter.ACC_ID,G_id);
userInfo.put(AccountCenter.ACC_NAME,G_name);
userInfo.put(AccountCenter.ACC_EMAIL,G_email);
userInfo.put(AccountCenter.ACC_PROFILE_IMAGE,G_url);

//问题在这里
//附加个人资料信息
com.google.api.services.people.v1.People peopleService = PeopleHelper.setUp(activity,acct.getServerAuthCode( ));

com.google.api.services.people.v1.model.Person profile = peopleService.people()。get(people / me)
.setRequestMaskIncludeField(person.genders 。,person.urls,person.birthdays)执行();

if(!profile.isEmpty()){

List< Url> urls = profile.getUrls();
列表<性别>性别= profile.getGenders();
列表<生日> birthdays = profile.getBirthdays();

字符串G_link = urls.get(0).getValue();
String G_gender = genders.get(0).getValue();
日期bday = birthdays.get(0).getDate();
String G_birthday = String.format(%02d,bday.getDay())+ - + String.format(%02d,bday.getMonth())+ - + String.format (%04d,bday.getYear()); //检查:如果未显示,年份将为0000,可以为空?

userInfo.put(AccountCenter.ACC_URL,G_link);
userInfo.put(AccountCenter.ACC_GENDER,G_gender);
userInfo.put(AccountCenter.ACC_BIRTHDAY,G_birthday);
}

AccountCenter.setUserInfo(activity,userInfo.toString(),Constants.ACCOUNT_TYPE_GOOGLE);
memberSocialLogin(activity,userInfo,Constants.ACCOUNT_TYPE_GOOGLE,Constants.PROVIDER_NAME_GOOGLE);

catch(IOException ie){
ie.printStackTrace();
返回ie.toString();
} catch(Exception e){
e.printStackTrace();
return e.toString();
}

返回1;
}

@Override
protected void onPostExecute(String response){
super.onPostExecute(response); $!
$ b $ if if(!response.equals(1)){
GeneralMethods.hideProgressDialog();

if(mGoogleSignedInListener!= null){
mGoogleSignedInListener.onError(response);




code
$ b

PeopleHelper :

  public class PeopleHelper {

private static final String APPLICATION_NAME =Grapps; // any名称

public static People setUp(final Context context,String serverAuthCode){

String progress =0%;

尝试{

HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

//为基于Web的应用程序重定向URL。
//也可以为空。
String redirectUrl =;

progress =10%;

//这里的问题
//访问令牌的交换授权码
GoogleTokenResponse tokenResponse =新的GoogleAuthorizationCodeTokenRequest(
httpTransport,
jsonFactory,
Constants.Google_Client_ID,
Constants.Google_Client_Secret,
serverAuthCode,
redirectUrl).execute();

progress =40%;

//使用来自GoogleTokenResponse的令牌创建GoogleCredential对象
GoogleCredential凭证=新的GoogleCredential.Builder()
.setClientSecrets(Constants.Google_Client_ID,Constants.Google_Client_Secret)
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.build();

progress =60%;

credential.setFromTokenResponse(tokenResponse);

progress =80%;

//凭证可用于访问Google服务
返回新的People.Builder(httpTransport,jsonFactory,凭证)
.setApplicationName(APPLICATION_NAME)
.build ();

} catch(IOException e){

final String finalProgress = progress +\\\
+ e.toString();

Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable(){
public void run(){
GeneralMethods.showAlert(context,设置人员错误,finalProgress);
}
});

返回null;



$ b


解决方案

如果在Google控制台和代码中没有问题,请尝试查看Android项目设置,在build.gradle中设置minifyEnabled false可能会有所帮助。

  buildTypes {
release {
// minifyEnabled true
// shrinkResources true
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard -android.txt'),'proguard-rules.pro'
}
}


I've used up my way. I followed the tutorial(part 1 and 2) to use Google People API in my android project. It always hit an error saying parameter code is missing in the signed apk, and stucked at getting GoogleTokenResponse. It works fine in the debug version. What did I do wrong?

And I have done all these:

  • Changed SHA1 to released version.
  • Replace downloaded google-services.json file downloaded from Firebase.
  • Client ID and Client Secret using OAuth Client ID for web
  • Invalidate caches/Restart.
  • Delete and recreate credential.

Google Sign In class:

public void Google_signIn() {

        //migrate to people api
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                // The serverClientId is an OAuth 2.0 web client ID
                .requestServerAuthCode(Constants.Google_Client_ID)
                .requestEmail()
                .requestScopes(new Scope(Scopes.PLUS_LOGIN),
                        new Scope(PeopleScopes.USERINFO_EMAIL))
                .build();

        if (mGoogleApiClient == null) {

            mGoogleApiClient = new GoogleApiClient.Builder(activity)
                    .enableAutoManage(activity /* FragmentActivity */, this /* OnConnectionFailedListener */)
                    .addOnConnectionFailedListener(this)
                    .addConnectionCallbacks(this)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .addApi(LocationServices.API)
                    .build();
        }

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        activity.startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
    }

Handler result after signing in successfully:

GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
            new PeoplesAsync().execute(result);
        }

PeoplesAsync:

class PeoplesAsync extends AsyncTask<GoogleSignInResult, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(GoogleSignInResult... params) {

            GoogleSignInAccount acct = params[0].getSignInAccount();
            JSONObject userInfo = new JSONObject();

            try {

                //basic profile information
                String G_id = acct.getId();
                String G_email = acct.getEmail();
                String G_name = acct.getDisplayName();
                String G_url = acct.getPhotoUrl().toString();//profile img

                userInfo.put(AccountCenter.ACC_ID, G_id);
                userInfo.put(AccountCenter.ACC_NAME, G_name);
                userInfo.put(AccountCenter.ACC_EMAIL, G_email);
                userInfo.put(AccountCenter.ACC_PROFILE_IMAGE, G_url);

                //problem here
                //additional profile information
                com.google.api.services.people.v1.People peopleService = PeopleHelper.setUp(activity, acct.getServerAuthCode());

                com.google.api.services.people.v1.model.Person profile = peopleService.people().get("people/me")
                        .setRequestMaskIncludeField("person.genders,person.urls,person.birthdays").execute();

                if (!profile.isEmpty()) {

                    List<Url> urls = profile.getUrls();
                    List<Gender> genders = profile.getGenders();
                    List<Birthday> birthdays = profile.getBirthdays();

                    String G_link = urls.get(0).getValue();
                    String G_gender = genders.get(0).getValue();
                    Date bday = birthdays.get(0).getDate();
                    String G_birthday = String.format("%02d", bday.getDay()) + "-" + String.format("%02d", bday.getMonth()) + "-" + String.format("%04d", bday.getYear());// check: year will be 0000 if not shown, can be null ?

                    userInfo.put(AccountCenter.ACC_URL, G_link);
                    userInfo.put(AccountCenter.ACC_GENDER, G_gender);
                    userInfo.put(AccountCenter.ACC_BIRTHDAY, G_birthday);
                }

                AccountCenter.setUserInfo(activity, userInfo.toString(), Constants.ACCOUNT_TYPE_GOOGLE);
                memberSocialLogin(activity, userInfo, Constants.ACCOUNT_TYPE_GOOGLE, Constants.PROVIDER_NAME_GOOGLE);

            } catch (IOException ie) {
                ie.printStackTrace();
                return ie.toString();
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            }

            return "1";
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);

            if (!response.equals("1")) {
                GeneralMethods.hideProgressDialog();

                if (mGoogleSignedInListener != null) {
                    mGoogleSignedInListener.onError(response);
                }
            }
        }
    }

PeopleHelper:

public class PeopleHelper {

    private static final String APPLICATION_NAME = "Grapps";//any name

    public static People setUp(final Context context, String serverAuthCode) {

        String progress = "0%";

        try {

            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

            // Redirect URL for web based applications.
            // Can be empty too.
            String redirectUrl = "";

            progress = "10%";

            //problem here
            // Exchange auth code for access token
            GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                    httpTransport,
                    jsonFactory,
                    Constants.Google_Client_ID,
                    Constants.Google_Client_Secret,
                    serverAuthCode,
                    redirectUrl).execute();

            progress = "40%";

            // Create a GoogleCredential object using the tokens from GoogleTokenResponse
            GoogleCredential credential = new GoogleCredential.Builder()
                    .setClientSecrets(Constants.Google_Client_ID, Constants.Google_Client_Secret)
                    .setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .build();

            progress = "60%";

            credential.setFromTokenResponse(tokenResponse);

            progress = "80%";

            // credential can then be used to access Google services
            return new People.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(APPLICATION_NAME)
                    .build();

        } catch (IOException e) {

            final String finalProgress = progress + "\n" + e.toString();

            Handler handler = new Handler(context.getMainLooper());
            handler.post(new Runnable() {
                public void run() {
                    GeneralMethods.showAlert(context, "Error setting up People", finalProgress);
                }
            });

            return null;
        }
    }

}

解决方案

If there aren’t issues in Google Console and code, try look into Android project setting, set minifyEnabled false in build.gradle might help.

buildTypes {
    release {
//            minifyEnabled true
//            shrinkResources true
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

这篇关于Android Google People API错误:TokenResponseException:缺少参数:代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆