C#使用.NET Framework的网络功能

   2024-09-30 5900
核心提示:在C#中,使用.NET Framework的网络功能可以通过多种方式实现HttpWebRequest 和 HttpWebResponse:这两个类用于发送HTTP请求并接

在C#中,使用.NET Framework的网络功能可以通过多种方式实现

HttpWebRequest 和 HttpWebResponse:这两个类用于发送HTTP请求并接收HTTP响应。
using System;using System.IO;using System.Net;namespace NetworkExample{    class Program    {        static void Main(string[] args)        {            string url = "https://www.example.com";            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);            request.Method = "GET";            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            StreamReader reader = new StreamReader(response.GetResponseStream());            string content = reader.ReadToEnd();            Console.WriteLine("Status Code: " + response.StatusCode);            Console.WriteLine("Content: " + content);            response.Close();        }    }}
WebClient:这是一个简化的类,用于发送HTTP请求并接收HTTP响应。
using System;using System.Net;namespace NetworkExample{    class Program    {        static void Main(string[] args)        {            using (WebClient client = new WebClient())            {                string url = "https://www.example.com";                string content = client.DownloadString(url);                Console.WriteLine("Content: " + content);            }        }    }}
HttpClient:这是一个更高级的类,用于发送HTTP请求并接收HTTP响应。它提供了异步操作和更好的性能。
using System;using System.Net.Http;using System.Threading.Tasks;namespace NetworkExample{    class Program    {        static async Task Main(string[] args)        {            using (HttpClient client = new HttpClient())            {                string url = "https://www.example.com";                HttpResponseMessage response = await client.GetAsync(url);                string content = await response.Content.ReadAsStringAsync();                Console.WriteLine("Status Code: " + response.StatusCode);                Console.WriteLine("Content: " + content);            }        }    }}

TcpClient 和 TcpListener:这两个类用于创建TCP客户端和服务器。

UdpClient:这个类用于创建UDP客户端和服务器。

NetworkInformation:这个命名空间包含用于获取网络接口信息、IP地址和其他网络相关信息的类。

这些示例展示了如何使用.NET Framework的网络功能。根据你的需求,你可以选择适合你的场景的类和方法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号