troubles with google calendar builder service

2019-04-17 07:09发布

问题:

I am developing an application on android. My app uses a Google Calendar Api, now I want to include Google Drive Api, so I have changed somes libs. And my Calendar Service Builder has a deprecated line of code, this:

GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accesstoken);

Before the change of the libs I used.:

import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;

But right now, I don't use the first line of code, it's deprecated, and I need something similar.

This was my first calendar builder service:

public static Calendar build(String accessToken)
        {
        HttpTransport transport    = AndroidHttp.newCompatibleTransport();
        JacksonFactory jsonFactory = new JacksonFactory();

        GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);


        Calendar service = Calendar.builder(transport, jsonFactory).setApplicationName(Constants.APP_NAME).setJsonHttpRequestInitializer(new JsonHttpRequestInitializer()
            {
            @Override
            public void initialize(JsonHttpRequest request)
                {
                CalendarRequest calendarRequest = (CalendarRequest) request;
                calendarRequest.setKey(Constants.API_KEY);
                }
            }).setHttpRequestInitializer(accessProtectedResource).build();
        return service;
        }
    }

And now I'm trying that, but it isn't work:

public static Calendar build(TokenResponse tokenResponse)
        {
        HttpTransport transport    = AndroidHttp.newCompatibleTransport();
        JacksonFactory jsonFactory = new JacksonFactory();


        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(tokenResponse);
        Log.w("1","1"+credential);


        Calendar service = Calendar.builder(transport, jsonFactory).setApplicationName(Constants.APP_NAME).setJsonHttpRequestInitializer(new JsonHttpRequestInitializer()
            {
            @Override
            public void initialize(JsonHttpRequest request)
                {
                CalendarRequest calendarRequest = (CalendarRequest) request;
                calendarRequest.setKey(Constants.API_KEY);
                }
            }).setHttpRequestInitializer(credential).build();
        return service;
        }
    }

But it never show the log.

回答1:

Make the following change in the above code to get it working

static String authToken; 
HttpRequestInitializer requestInitializer = new HttpRequestInitializer() {
      public void initialize(HttpRequest request) throws IOException {
        request.getHeaders().setAuthorization(GoogleHeaders.getGoogleLoginValue(authToken));
      }
    };
    Calendar service = new Calendar.Builder(transport, jsonFactory, requestInitializer)