2012-03-09 3 views
0

Google에서 사용자의 캘린더에 액세스하기위한 인증 코드가있어 액세스 토큰을 바꾸려고합니다. 자신의 문서에 따르면Google 캘린더 API - 잘못된 요청 (400) 액세스 토큰 코드를 바꾸려고 시도합니다.

실제 요청과 같습니다

POST /o/oauth2/token HTTP/1.1 
Host: accounts.google.com 
Content-Type: application/x-www-form-urlencoded 

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu& 
client_id=8819981768.apps.googleusercontent.com& 
client_secret={client_secret}& 
redirect_uri=https://oauth2-login-demo.appspot.com/code& 
grant_type=authorization_code 

(C#을)은 다음과 같이이가 액세스 할 내 시도 :

string url = "https://accounts.google.com/o/oauth2/token"; 
WebRequest request = HttpWebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 

string body = "code=<the_code_I_received>&\r\n" 
    + "client_id=<my_client_id>&\r\n" 
    + "client_secret=<my_client_secret>&\r\n" 
    + "redirect_uri=http://localhost:4300\r\n" 
    + "grant_type=authorization_code&\r\n" 
          ; 
byte[] bodyBytes = Encoding.ASCII.GetBytes(body); 
request.ContentLength = bodyBytes.Length ; 
Stream bodyStream = request.GetRequestStream(); 
bodyStream.Write(bodyBytes, 0, bodyBytes.Length); 
bodyStream.Close(); 

try 
{ 
    request.GetResponse(); 

'HTTP : // localhost : 4300 '은 원래 요청에 넣은 것과 정확히 똑같습니다 (그 포트에서 웹 서버로 수신 대기하여 코드를 다시 얻었으므로 유효했습니다). 그러나'http : // localhost '그냥 경우에.

프록시를 null (변경하지 않음)으로 설정하고 수락 (웹 요청에 해당 헤더를 추가 할 수 없음)을 변경하는 등 여러 가지 제안을 시도했습니다.

각각의 경우 HTTP 400 - 나쁜 요청이 다시 발생합니다 (try/catch는 예외가 발생 함).

/token 다음에 슬래시를 넣으면 (아무 것도 시도하지 않겠습니다!) 500 내부 서버 오류가 발생 했으므로 그 중 하나도 아닙니다.

내가 뭘 잘못하고 있는지 아는 사람이 있습니까?

답변

0

본문에 새 줄 \ r \ n이 필요합니까? 이 코드는 나를 위해 ...

var req0 = WebRequest.Create("https://accounts.google.com/o/oauth2/token"); 
req0.Method = "POST"; 
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", 
code, //the code i got back 
"2xxx61.apps.googleusercontent.com", "XJxxxFy", 
"http://localhost:1599/home/oauth2callback"); //my return URI 

byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
req0.ContentType = "application/x-www-form-urlencoded"; 
req0.ContentLength = byteArray.Length; 
using (Stream dataStream = req0.GetRequestStream()) 
{ 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    dataStream.Close(); 
} 
try 
{ 
using (WebResponse response = req0.GetResponse()) 
    { 
    using (var dataStream = response.GetResponseStream()) 
     {  
     using (StreamReader reader = new StreamReader(dataStream)) 
     { 
     string responseFromServer = reader.ReadToEnd(); 
     var ser = new JavaScriptSerializer(); 
      accessToken = ser.DeserializeObject(responseFromServer); 
     } 
    } 
} 
} 
catch (WebException wex){ var x = wex; } 
catch (Exception ex){var x = ex;}