2012-03-09 17 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 'は私が元のリクエストに入れたものとまったく同じです(そして、そのポートのWebサーバーとしてリスニングしてコードを取得したので有効でした)が、http:// localhostただ 万一に備えて。

プロキシをnull(変更なし)に設定し、Accept(Web要求にそのヘッダーを追加することはできません)を変更するなど、さまざまな提案を試しました。

いずれの場合も、HTTP 400 - 悪質な要求が戻されます(try/catchの発動には例外があります)。

/トークンの後にスラッシュを付けると(何か試してみます)、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;} 
関連する問題