2013-10-17 1 views
0

GoogleApi로 작업하고 있습니다. 나는 Google api를 사용하여 응답으로 accesstoken을 받고 싶습니다. 내가 사용했을 때 나는 토큰 다음HttpWebRequest 메소드 GET/POST가 작동하지 않습니까?

을 액세스를 얻기 위해의 HttpWebRequest를 보낸다 때 : - request.Method = "POST"

예외 : - HTTP 메소드 POST이 URL

내가 사용을 지원하지 않습니다 : - request.Method은 = "GET"

예외 : - System.Net.ProtocolViolationException :

,536,913이 동사 형으로 콘텐츠 바디를 보낼 수 없습니다 것은

실제 요구처럼 보일 수 있습니다 다음과 63,210

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

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

성공적인 응답이 JSON 배열로 반환됩니다, 유사한

{ 
    "access_token":"1/fFAGRNJru1FTz70BzhT3Zg", 
    "expires_in":3920, 
    "token_type":"Bearer" 

}

내 코드입니다 : -

var request = (HttpWebRequest)WebRequest.Create(@"https://accounts.google.com"); 
    request.Method = "POST"; 
    request.ContentType = "application/json"; 
    //request.KeepAlive = false; 

    // request.Headers[HttpRequestHeader.Authorization] = ""; 
    //request.ContentLength = 0; 

    using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream())) 
    { 
     string json = "{\"code\":\"4/M1IIC8htCuvYORuVJK16oadDb3Gd.cigIKgaPjvUYXE-sT2ZLcbSrckCLgwI\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"," + "\"client_secret\":\"MXjKvevD_cKp5eQWZ1RFXfdo\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"grant_type\":\"authorization_code\"}"; 

     streamWriter.Write(json); 
     // streamWriter.Flush(); 
     //streamWriter.Close(); 
    } 
    try 
    { 
     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
     { 
      StreamReader responsereader = new StreamReader(response.GetResponseStream()); 

      var responsedata = responsereader.ReadToEnd(); 
      //Session["responseinfo"] = responsereader;  
     } 
    } 
    catch (WebException ex) 
    { 
     using (WebResponse response = ex.Response) 
     { 
      var httpResponse = (HttpWebResponse)response; 

      using (Stream data = response.GetResponseStream()) 
      { 
       var sr = new StreamReader(data); 
       throw new Exception(sr.ReadToEnd()); 
      } 
     } 
    } 

답변

1

이 문제입니다 :

var request = (HttpWebRequest)WebRequest.Create(@"https://accounts.google.com"); 

원래 표시 한 URL이 아닙니다. 도메인 루트 일뿐입니다.

var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); 

내가 줄 바꿈 또는 백 슬래시를 포함하지 않는 문자열로 @을 제거, 그래서 리터럴 그대로 문자열을 사용에는 효과가 없습니다 : 당신이 필요합니다. 내가 사용하지만, "오류"줄의 "INVALID_REQUEST를"- :

+0

을 -

(? 그렇지 또한, 나는이 구글 클라이언트 API를에 포함되는 기대). –

+0

@AnuragJain : 그러면 잘못된 코드를 사용하고있는 것입니다. 브라우저에서 이미 사용했던 것을 재사용하려는 경우 (예를 들어) 문제가있을 수 있습니다. –

+0

: - 코드가 유효하지 않다는 것은 URL에서 전달하는 매개 변수가 잘못되었음을 의미합니다. –

관련 문제