0

我正在尝试使用以下代码通过 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.

我该怎么办?

4

1 回答 1

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);
于 2013-01-31T08:02:13.583 回答