【问题标题】:Getting error while fetching information from windows live server从 Windows Live 服务器获取信息时出错
【发布时间】:2013-01-31 07:14:07
【问题描述】:

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

我该怎么办?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多