Authorizing Requests to the Google Calendar API only once time in Java -
i looking in google calendar in java api , got confused.
my problem this: when run application generates url when put in browser generates code. wondering how next time running application not need url generate code, wonder if possible make these steps once!
here's code:
public void setup() throws ioexception, generalsecurityexception { httptransport httptransport = googlenethttptransport.newtrustedtransport(); jacksonfactory jsonfactory = jacksonfactory.getdefaultinstance(); // clientid , clientsecret can found in google developers console string clientsecret = "0xgfteyxdjtyqitwhd6ytxnt"; // or redirect url web based applications. string redirecturl = "urn:ietf:wg:oauth:2.0:oob"; string scope = "https://www.googleapis.com/auth/calendar"; googleauthorizationcodeflow flow = new googleauthorizationcodeflow( httptransport, jsonfactory, client_id, clientsecret, collections.singleton(scope)); // step 1: authorize string authorizationurl = flow.newauthorizationurl().setredirecturi(redirecturl).build(); // point or redirect user authorizationurl. system.out.println("go following link in browser:"); system.out.println(authorizationurl); // read authorization code standard input stream. bufferedreader in = new bufferedreader(new inputstreamreader(system.in)); system.out.println("what authorization code?"); string code = in.readline(); // end of step 1 // step 2: exchange googletokenresponse response = flow.newtokenrequest(code).setredirecturi(redirecturl) .execute(); // end of step 2 credential credential = new googlecredential.builder() .settransport(httptransport).setjsonfactory(jsonfactory).setclientsecrets(client_id, clientsecret) .build().setfromtokenresponse(response); service = new calendar.builder(httptransport, jsonfactory, credential).setapplicationname("your_application_name").build(); }
the flow
you send client id / secret , url authentication.
using url authenticate , code.
you exchange code access_token.
this access token can used api specific time ( 1 hour )
so can generate access_tone once , can use hour instead of generating again , again.
static { timer timer = new timer(); timer.schedule(new timertask() { public void run() { synchronized(singleton.class) { access_token = new methodtoinitializeaccesstoken(); } } }, 60 * 60 * 1000l /* once per hour */); }
Comments
Post a Comment