从 Windows Live 服务器获取信息时出错

本文关键字:信息 出错 获取 服务器 Windows Live | 更新日期: 2023-09-27 17:56:59

我正在尝试使用以下代码通过Windows Real帐户对用户进行身份验证。

byte[] byteArray = Encoding.UTF8.GetBytes(postData);
 WebRequest request = WebRequest.Create("https://oauth.live.com/token");
 request.ContentType = "application/x-www-form-urlencoded";
 request.ContentLength = byteArray.Length;
 request.Method = "POST"; 
 Stream resp = request.GetRequestStream();
 Stream dataStream = request.GetRequestStream();
 dataStream.Write(byteArray, 0, byteArray.Length);
 var response = request.GetResponse();

但是我在最后一行出现以下错误。

The remote server returned an error: (400) Bad Request.

我应该为此做什么?

从 Windows Live 服务器获取信息时出错

您的问题可能是因为我们没有在"application/x-www-form-urlencoded"帖子上发送字节,而是一个字符串。此外,GetRespose看起来不像正确的。您的代码必须如下所示:

// I do not know how you create the byteArray
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// but you need to send a string
string strRequest = Encoding.ASCII.GetString(byteArray);
WebRequest request = WebRequest.Create("https://oauth.live.com/token");
request.ContentType = "application/x-www-form-urlencoded";
// not the byte length, but the string
//request.ContentLength = byteArray.Length;
request.ContentLength = strRequest.Length;
request.Method = "POST"; 
using (StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
{
    streamOut.Write(strRequest);
    streamOut.Close();
}
string strResponse;
// get the response
using (StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
{
    strResponse = stIn.ReadToEnd();
    stIn.Close();
}
// and here is the results
FullReturnLine = HttpContext.Current.Server.UrlDecode(strResponse);