I'm trying to set up offline access for a Google Analytics API application using OAuth2 and I'm using ASP.NET to POST my authorization code in exchange for a refresh token but I can't get a response from the server to give me the refresh token.
I've used the example code from the MSDN documentation for a post request so I can only assume this is correct, however I receive the error message "The remote server returned an error: (400) Bad Request at System.Net.HttpWebRequest.GetResponse()":
using System;
using System.IO;
using System.Net;
using System.Text;
WebRequest request = WebRequest.Create ("https://accounts.google.com/o/oauth2/token?code=xxxmyauthorizationcodexxx&client_id=xxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxx&redirect_uri=https://mysite.com/oauth2callback&grant_type=authorization_code");
request.Method = "POST";
string postData = "code=xxxmyauthorizationcodexxx&client_id=xxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxx&redirect_uri=https://mysite.com/oauth2callback&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
WebResponse response = request.GetResponse ();
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
reader.Close ();
dataStream.Close ();
response.Close ();
I have successfully used the GET method to retrieve the authorization code to begin with and I'm following this documentation: https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse
I'm also using a https website to make the requests and I'm manually refreshing my authorization code as it expires. Does anyone have a solution for this problem?
EDIT: For anyone experiencing the same issue, firstly look at aeijdenberg's response below, but my solution was that the authorization code I used for the code parameters expires pretty instantaneously - I kept refreshing my page without request a new one. To get the data just display the content from the responseFromServer variable.