title: Google Data Api returning an invalid access token
body: <p>I'm trying to pull a list of contacts from a google account. But Google returns a 401. </p>
  
  <p>The url used for requesting an authorization code:</p>
  
  <pre><code>String codeUrl = 'https://accounts.google.com/o/oauth2/auth' + '?'
             + 'client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8')
             + '&amp;redirect_uri=' + EncodingUtil.urlEncode(MY_URL, 'UTF-8')
             + '&amp;scope=' + EncodingUtil.urlEncode('https://www.google.com/m8/feeds/', 'UTF-8')
             + '&amp;access_type=' + 'offline'
             + '&amp;response_type=' + EncodingUtil.urlEncode('code', 'UTF-8')
             + '&amp;approval_prompt=' + EncodingUtil.urlEncode('force', 'UTF-8');
  </code></pre>
  
  <p>Exchanging the returned authorization code for an access token (and refresh token):</p>
  
  <pre><code>String params = 'code=' + EncodingUtil.urlEncode(authCode, 'UTF-8')
                + '&amp;client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8')
                + '&amp;client_secret=' + EncodingUtil.urlEncode(CLIENT_SECRET, 'UTF-8')
                + '&amp;redirect_uri=' + EncodingUtil.urlEncode(MY_URL, 'UTF-8')      
                + '&amp;grant_type=' + EncodingUtil.urlEncode('authorization_code', 'UTF-8');  
  
  Http con = new Http();
  Httprequest req = new Httprequest();
  req.setEndpoint('https://accounts.google.com/o/oauth2/token');
  req.setHeader('Content-Type', 'application/x-www-form-urlencoded');                   
  req.setBody(params);
  req.setMethod('POST');
  Httpresponse reply = con.send(req); 
  </code></pre>
  
  <p>Which returns a JSON array with what looks like a valid access token:</p>
  
  <pre><code>{ 
      "access_token" : "{access_token}", 
      "token_type" : "Bearer", 
      "expires_in" : 3600, 
      "refresh_token" : "{refresh_token}" 
  } 
  </code></pre>
  
  <p>However when I try and use the access token (either in code or curl) Google returns a 401: </p>
  
  <pre><code>curl -H "Authorization: Bearer {access_token}"  https://www.google.com/m8/feeds/contacts/default/full/
  </code></pre>
  
  <p>Incidentally the same curl command but with an access token acquired via <a href="https://code.google.com/oauthplayground/" rel="nofollow">https://code.google.com/oauthplayground/</a> works. Which leads me to believe there is something wrong with the exchanging authorization code for access token request as the returned access token does not work.   </p>
  
  <p>I should add this is all within the expires_in time frame so its not that the access_token has  expired</p>