4
votes

I'm trying to retrieve the oauth access token to make calls to some google apis in asp.net mvc, and I wrote the following code for an action:

        public ActionResult GetOAuthToken()
        {

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

        // Create a request using a URL that can receive a post. 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Host = "accounts.google.com";
        // Create POST data and convert it to a byte array.
        string postData = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"].ToString(), OAuthConfig.client_id, OAuthConfig.client_secret, OAuthConfig.token_redirect_uri);
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byteArray = encoding.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();

        // SOME CODE TO PROCESS THE RESPONSE

        Response.Redirect("/Home");
        return View();
        }

OAuthConfig is just a class that contains the client id, client secret etc.

I keep getting 'The remote server returned an error: (400) Bad Request.' at the request.GetResponse() line. Where am I going wrong?

1
Is there a response body? What does it say?spender
There is none. An exception is thrown at the line request.GetResponse()niravb
There almost certainly is. Catch the WebException and check out its properties. msdn.microsoft.com/en-us/library/…spender
I did examine the WebException using the debugger, but I didn't find anything useful there. Where exactly do you find the response body?niravb
catch(WebException ex){ var response = ex.Response; ...}? If it's non-null, decode the response stream. It could contain more info.spender

1 Answers

1
votes

Google does provide a higher level library to work with its services, this handles the formatting of the urls and I find it makes it a lot easier to work with their apis. See http://code.google.com/p/google-api-dotnet-client/