2014-01-21 6 views
0

Google의 oAuth (v2)를 통해 액세스 토큰을 얻으려고합니다. ASP.NET 4.0 Web Forms (C#)을 사용하고 있습니다. 문제는 HttpWebRequest를 제출할 때 잘못된 요청 오류가 발생하는 것입니다. 여기에서 찾은 코드 (http://blog.movereem.nl/using-google-apis-through-oauth-20/)를 사용하고 있습니다. 이것은 내 pageLoad 이벤트에있는 코드입니다.Google 캘린더 oAuth 나쁜 요청

  string strCode = ""; 
     string strClientID = "********.apps.googleusercontent.com"; 
     string strClientSecret = "**********"; 
     string strRedirectURI = "http://www.example.com"; 

     if (Request.QueryString["code"] != null && Request.QueryString["code"].ToString() != "") 
     { 
      strCode = Request.QueryString["code"].ToString(); 
      StreamWriter sw = new StreamWriter(Server.MapPath("~\\") + "code.txt"); 
      sw.WriteLine(Request.QueryString["code"].ToString()); 
      sw.Close(); 


      string queryStringFormat = "code={0}&redirect_uri={1}&client_id={2}&client_secret={3}&grant_type=authorization_code"; 
      string postcontents = string.Format(queryStringFormat 
               , HttpUtility.UrlEncode(strCode) 
               , HttpUtility.UrlEncode(strClientID) 
               , HttpUtility.UrlEncode(strClientSecret) 
               , HttpUtility.UrlEncode(strRedirectURI)); 
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://accounts.google.com/o/oauth2/token"); 
      request.Method = "POST"; 
      byte[] postcontentsArray = Encoding.UTF8.GetBytes(postcontents); 
      request.ContentType = "application/x-www-form-urlencoded"; 
      request.ContentLength = postcontentsArray.Length; 
      using (Stream requestStream = request.GetRequestStream()) 
      { 
       requestStream.Write(postcontentsArray, 0, postcontentsArray.Length); 
       requestStream.Close(); 
       WebResponse response = request.GetResponse();//Error Happens Here 
       using (Stream responseStream = response.GetResponseStream()) 
       using (StreamReader reader = new StreamReader(responseStream)) 
       { 
        string responseFromServer = reader.ReadToEnd(); 
        reader.Close(); 
        responseStream.Close(); 
        response.Close(); 
        //return SerializeToken(responseFromServer); 
       } 
      } 
     } 

어떤 도움을 주실 수 있습니다. 감사. 코드는 일반적으로 올바른 보이는 언뜻

답변

0

그러나 나는 당신이 당신의 queryStringFormat와 다른 순서로 string.Format 인수를 생각 :

string queryStringFormat = "code={0}&redirect_uri={1}&client_id={2}&client_secret={3}&grant_type=authorization_code"; 
string postcontents = string.Format(queryStringFormat 
         , HttpUtility.UrlEncode(strCode) 
         // Redirect URI should be here (or switch the order above) 
         , HttpUtility.UrlEncode(strClientID) 
         , HttpUtility.UrlEncode(strClientSecret) 
         , HttpUtility.UrlEncode(strRedirectURI));