Search code examples
javahttphttpsgoogle-oauth

How To Send HTTP Request To Google API Like in Google Oauth Playground?


I tried the google oauth playground here: https://developers.google.com/oauthplayground/


Step 1, I choose calendar API v3, then asked for permission -> I select my google account and clicked "allow"

Step 2, I clicked "Exchange authorization code for tokens"

Step 3, I typed "https://www.googleapis.com/calendar/v3/calendars/primary/events" (choosing to list all events that I have), then clicked "Send the request" -> the output is HTTP response containing list of my events in my primary calendar in json format


My question is: Can I use the google API (especially calendar) just like this via HTTP Request-Response?

Basically I want to make the HTTP request as shown in the playground, and get the HTTP response as shown in the playground

(for example: using java socket programming like below)

        String httpsURL = "https://accounts.google.com/o/oauth2/token";

        String query = "code="+("123123123123codehere"); 
        query += "&client_id="+("123123123123.apps.googleusercontent.com");
        query += "&client_secret="+("123123123123");
        query += "&redirect_uri="+("urn:ietf:wg:oauth:2.0:oob");
        query += "&grant_type="+("authorization_code");

        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-length", String.valueOf(query.length())); 

        con.setDoOutput(true); 
        con.setDoInput(true); 

        DataOutputStream output = new DataOutputStream(con.getOutputStream());  

        output.writeBytes(query);
        output.close();
        DataInputStream input = new DataInputStream( con.getInputStream() ); 

        for( int c = input.read(); c != -1; c = input.read() ) 
        System.out.print( (char)c ); 
        input.close(); 

        System.out.println("Resp Code:"+con .getResponseCode()); 
        System.out.println("Resp Message:"+ con .getResponseMessage());

these code didn't work and the output is blank (why? the string httpRequest is copy pasted exactly as in the oauth playground, and the token haven't expired yet)

Also I plan to use these in php with curl, can it be done?


Solution

  • Google APIs like calendar API are just rest APIs which means that they run over HTTP GET and HTTP Post requests.

    You can easily send the raw http posts and gets to google and get your responses back.

    The access token you get will expire after one hour. A refresh token will not expire and is used to get a new access token when it does expire. I have a tutorial on Google 3 legged oauth2 flow

    you might want to consider using the Google Java client library though it will be easier.