我正在尝试使用此代码
从windows live connect api获取访问令牌string requestUrl =“https://consent.live.com/AccessToken.aspx”;
// Request the access token.
string postData = string.Format("{0}?wrap_client_id={1}&wrap_client_secret={2}&wrap_callback={3}&wrap_verification_code={4}&idtype={5}",
requestUrl,
"000000004C039809",
"l4VJekL1vFL1iFVmcP5qLkWv9ukY4mdl",
"http://ewshops.com",
"dac5d71d-d640-30d1-ebed-3576b132b3ec",
"cid");
byte[] postDataEncoded = System.Text.Encoding.UTF8.GetBytes(postData);
WebRequest req = HttpWebRequest.Create(requestUrl);
req.Method = "POST";
// req.
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postDataEncoded.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataEncoded, 0, postDataEncoded.Length);
WebResponse res = req.GetResponse();
string responseBody = null;
using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
{
responseBody = sr.ReadToEnd();
}
// Process FORM POST.
NameValueCollection responseCollection = System.Web.HttpUtility.ParseQueryString(responseBody);
return responseCollection["wrap_access_token"];
但我收到了以下错误
远程服务器返回错误:(401)未经授权。
答案 0 :(得分:2)
向我们展示响应主体,它通常包含更多信息。在将其添加到uri之前,您还应该对其进行urlencode http://ewshops.com
。
答案 1 :(得分:2)
我遇到了同样的问题并修复如下。删除requestUrl(“https://consent.live.com/AccessToken.aspx”)和随后的“?”来自你的postData。 POST数据应采用x-www-form-urlencoded格式,不包括请求URL。还有HttpUtility.UrlEncode()所有参数。