为什么WebResponse.StatusCode == HttpStatusCode.OK返回false?

时间:2016-10-22 08:02:26

标签: c#

我使用此代码验证c#中的Twitter电子邮件和密码,但它返回false,我不知道为什么? 另外,我想返回xml来读取它的用户名。

bool Result = false;

// A try except block to handle any exceptions
try
{
    // Encode the user name with password
    string UserPass = Convert.ToBase64String(
        System.Text.Encoding.UTF8.GetBytes(email + ":" + password));

    // Create our HTTP web request object
    HttpWebRequest Request =
        (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml");

    //Request.Proxy = WebProxy;
    //Request.Timeout = Timeout.Infinite;
    //Request.ReadWriteTimeout = Timeout.Infinite;
    //Request.KeepAlive = false;
    //Request.AllowAutoRedirect = false; // was true
    //Request.CookieContainer = cc;
    //Request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";

    // Set up our request flags and submit type
    Request.Method = "GET";
    Request.ContentType = "application/x-www-form-urlencoded";

    // Add the authorization header with the encoded user name and password
    Request.Headers.Add("Authorization", "Basic " + UserPass);

    // Use an HttpWebResponse object to handle the response from Twitter
    HttpWebResponse WebResponse = (HttpWebResponse)Request.GetResponse();

    string SourceCode = new StreamReader(WebResponse.GetResponseStream()).ReadToEnd();

    // Success if we get an OK response
    Result = WebResponse.StatusCode == HttpStatusCode.OK;
}
catch (Exception Ex)
{
    System.Diagnostics.Debug.WriteLine("Error: " + Ex.Message);
}

// Return success/failure

return Result;

1 个答案:

答案 0 :(得分:0)

实际上你的代码返回404找不到,这是catch,所以默认你将结果设置为false,它永远不会到达这一行

result = WebResponse.StatusCode == HttpStatusCode.OK;

所以结果是 false ;

另外,为了做到这一点,请按照这样的方式声明您的结果,

bool result = false;

而不是

  result = WebResponse.StatusCode == HttpStatusCode.OK;

只是做

if(WebResponse.StatusCode == HttpStatusCode.OK;)
{
  result =true;
}