如何发送HttpWebRequest并接收答案以检查c#中的互联网?

时间:2014-11-18 08:45:27

标签: c# httpwebrequest httpresponse

我试图使用httpwebrequest创建一个检查互联网连接(以及特殊网站的完整性)的应用。我在研究后发现了这段代码,但无法完成它并且不知道它是否属实:

 WebRequest myRequest = WebRequest.Create("http://www.bing.com");
            myRequest.Timeout = 5000;
            WebResponse response = myRequest.GetResponse();

            if(response == ???)
            {
                response.Close();
                return true;
            }
            else{
                response.Close();
                return false;
            }

我应该添加什么?

3 个答案:

答案 0 :(得分:2)

看看documentation

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create ("http://www.bing.com");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams and the response.
            reader.Close ();
            response.Close ();
        }
    }
}

[EDITED]

当然,您可以将您的响应转换为HttpWebResponse,并像这样询问StatusCode:

if ( ((HttpWebResponse)response).StatusCode == HttpStatusCode.OK )
{
    response.Close();
    return true;
}
else
{
    response.Close();
    return false;
}

答案 1 :(得分:2)

以这种方式尝试:

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.bing.com");
myRequest.Timeout = 5000;
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();

if(response.StatusCode == HttpStatusCode.OK)
{
  response.Close();
  return true;
}
else{
  response.Close();
  return false;
}

答案 2 :(得分:1)

如果您的ISP没有阻止ping流量,您也可以使用.net Ping Class

public static bool IsConnectedToInternet()
{
    string host = "www.google.com";
    bool result = false;
    Ping p = new Ping();
    try
    {
        PingReply reply = p.Send(host, 5000);
        if (reply.Status == IPStatus.Success)
            return true;
    }
    catch { }
    return result;
}