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

本文关键字:检查 互联网 答案 HttpWebRequest 何发送 | 更新日期: 2023-09-27 18:30:58

我正在尝试制作一个使用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;
            }

我应该添加什么?

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

试试这个方式:

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;
}

看看文档:

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 ();
        }
    }
}

[已编辑]

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

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

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

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;
}