我已经检查了stackoverflow并尝试了几种解决方案,但是当我尝试向google令牌服务器发送帖子请求以交换代码以获取oauth2令牌时,我仍然获得400。代码正在从查询字符串中正确检索。我已经尝试过对URL进行URL编码,重定向URL以及将请求中的编码更改为ASCII。我知道谷歌对标题很挑剔,但json响应是故意模糊的,只返回“错误:错误的请求”我无法调试请求的错误。我还尝试在chrome REST客户端中测试post请求并收到相同的错误。我认为标题中有错误或其他一些格式问题,但谷歌不会返回有用的错误代码。
//使用工作代码编辑
//trade code for token
public static String CodeTrade(String code)
{
String apiResponse;
string codeClient = "code=" + code + "&client_id=xxx.apps.googleusercontent.com&";
string secretUri = "client_secret=zzz&grant_type=authorization_code&redirect_uri=" + "https://web.locusvisual.com/gadgets/smallview/loginTrue.aspx";
string postData = codeClient + secretUri;
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
// Set the Method property of the request to POST.
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Create POST data and convert it to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
apiResponse = ((HttpWebResponse)response).StatusDescription.ToString();
//Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Console.ReadKey();
// Clean up the streams.
apiResponse = responseFromServer;
reader.Close();
dataStream.Close();
response.Close();
return apiResponse;
}
答案 0 :(得分:0)
在我看来你的urlencoding可能搞砸了。你urlencode locovisual.com网址,但没有别的。 400可靠意味着语法上会混淆你的请求。