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

时间:2013-01-31 07:14:08

标签: c# asp.net authentication windows-live

我正在尝试使用以下代码通过Windows Live帐户验证用户。

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.

我应该为此做些什么?

1 个答案:

答案 0 :(得分:0)

您的问题可能是因为我们不在“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);