0
我正在使用GoogleApi。我想通過Google API獲取accesstoken作爲響應。當我發送的HttpWebRequest爲獲得訪問令牌,然後HttpWebRequest方法GET/POST不工作?
當我使用: - request.Method = 「POST」
例外: - HTTP POST方法不受此URL
當我使用的支持: - request.Method =「GET」
例外: - System.Net.ProtocolViolationException:不能用這個動詞類型發送內容體
實際要求可能看起來像:
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());
}
}
}
: - 我用,但它給「錯誤」:「INVALID_REQUEST」。 –
@AuuragJain:然後,這表明你正在使用無效的代碼。如果您試圖重複使用已經在瀏覽器中使用過的瀏覽器(例如),那很可能是問題所在。 –
: - 無效的代碼意味着參數是錯誤的,我通過URL傳遞。 –