我正在尝试使用C#语言中的以下代码获取访问令牌,但我收到了400个错误的请求异常。
代码:
WebRequest httpWReq = WebRequest.Create("https://www.box.com/api/oauth2/token");
string postData = "grant_type=authorization_code";
postData += "&code=" + Code;
postData += "&client_id=MY_CLIENT_ID";
postData += "&client_secret=MY_CLIENT_SECRET";
postData += "&redirect_uri=https://www.google.com";
byte[] data = Encoding.UTF8.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoding";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = httpWReq.GetResponse();
var responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
var responseReader = reader.ReadToEnd();
MessageBox.Show(responseReader);
}
但我总是得到以下错误:
{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
如何克服这个问题?
任何帮助将不胜感激。在此先感谢。
谢谢, 哈里什雷迪
答案 0 :(得分:1)
我看到两个可能的问题,都是这一行:
postData += "&redirect_uri=https://www.google.com";
顺便提一下,您可能有兴趣查看GitHub和NuGet上的Box API v2 SDK for .Net(以及相应的MVC-based OAuth example)。 (完全披露:我对两者都有贡献。)
答案 1 :(得分:0)
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("https://api.box.com/oauth2/token");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "grant_type=authorization_code";
postData += "&code=" + authorizationCode;
postData += "&client_id=" + ClientId;
postData += "&client_secret=" + ClientSecretId;
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
//httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}