3

我正在尝试使用以下 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"}

如何克服这个问题?

任何帮助将不胜感激。提前致谢。

谢谢,哈里什·雷迪

4

2 回答 2

1

我看到两个可能的问题,都与这一行有关:

postData += "&redirect_uri=https://www.google.com";
  1. 我认为您需要对重定向 URI 进行 urlencode。
  2. 我认为您不拥有google.com域,因此这是一个无效值。:) 您需要重新指向您发出请求的域。或者更好的是,在 Box 应用程序的配置页面上预设此重定向 URI。

顺便说一句,您可能有兴趣查看 GitHub 和 NuGet 上的Box API v2 SDK for .Net(以及相应的基于 MVC 的 OAuth 示例)。(完全披露:我对两者都有贡献。)

于 2013-03-21T13:44:14.530 回答
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);
            }
于 2017-09-05T06:54:51.190 回答