C#网络编程System.Net.WebClient 类vs System.Net.Http.HttpClient 类

目录

一、WebClient 类

1.WebClient 将数据上传到资源的方法

2.WebClient 从资源下载数据的方法

3.示例源码

4.生成效果

二、HttpClient 类

1.示例源码

2.生成效果


        为什么要把两者拿出来pk呢?那是因为WebClient已经在.NET 6.0以后得版本被弃用了,一旦在.NET 6.0以上的框架下使用时,会产生SYSLIB0014 警告。虽然可以根据提示采取措施禁止警告,但已经是不正常的状态了。

        SYSLIB0014 警告 - .NET | Microsoft Learn  https://learn.microsoft.com/zh-cn/dotnet/fundamentals/syslib-diagnostics/syslib0014

        从 .NET 6 开始,将以下 API 标记为已过时。 在代码中使用这些 API 会在编译时生成警告 SYSLIB0014。并提示解决方法:请改用 HttpClient。

        WebRequest()
        System.Net.WebRequest.Create
        System.Net.WebRequest.CreateHttp
        System.Net.WebRequest.CreateDefault(Uri)
        HttpWebRequest(SerializationInfo, StreamingContext)
        System.Net.ServicePointManager.FindServicePoint
        WebClient()

一、WebClient 类

         命名空间:System.Net。提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。

        类 WebClient 提供用于将数据发送到或从 URI 标识的任何本地、Intranet 或 Internet 资源接收数据的常用方法。

        类 WebClient 使用 WebRequest 类提供对资源的访问权限。 WebClient实例可以访问使用 方法注册WebRequest.RegisterPrefix的任何WebRequest后代的数据。

1.WebClient 将数据上传到资源的方法

方法 说明
OpenWrite Stream检索用于将数据发送到资源的 。
OpenWriteAsync Stream检索用于将数据发送到资源的 ,而不会阻止调用线程。
UploadData 将字节数组发送到资源,并返回包含任何响应的 Byte 数组。
UploadDataAsync 在不 Byte 阻止调用线程的情况下,将数组发送到资源。
UploadFile 将本地文件发送到资源并返回包含任何响应的 Byte 数组。
UploadFileAsync 在不阻止调用线程的情况下,将本地文件发送到资源。
UploadValues 将 发送到 NameValueCollection 资源并返回包含任何响应的 Byte 数组。
UploadValuesAsync 将 发送到 NameValueCollection 资源并返回包含 Byte 任何响应的数组,而不会阻止调用线程。
UploadString 将 发送到 String 资源,并返回包含 String 任何响应的 。
UploadStringAsync 将 发送到 String 资源,而不会阻止调用线程。

2.WebClient 从资源下载数据的方法

方法 说明
OpenRead 以 的形式 Stream返回资源中的数据。
OpenReadAsync 从资源返回数据,而不会阻止调用线程。
DownloadData 从资源下载数据并返回 Byte 数组。
DownloadDataAsync 从资源下载数据并返回 Byte 数组,而不会阻止调用线程。
DownloadFile 将数据从资源下载到本地文件。
DownloadFileAsync 将数据从资源下载到本地文件,而不会阻止调用线程。
DownloadString String从资源下载 并返回 String。
DownloadStringAsync 从资源下载 , String 而不会阻止调用线程。

3.示例源码

// WebClient
// .NET 4.8控制台应用
// The following code example creates a WebClient instance 
// and then uses it to download data from a server and display it on the system console, 
// to download data from a server and write it to a file, 
// and to upload form values to a server and receive the response. 
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Download the data to a buffer.
                WebClient client = new WebClient();

                byte[] pageData = client.DownloadData("http://www.contoso.com");
                string pageHtml = Encoding.ASCII.GetString(pageData);
                Console.WriteLine(pageHtml);

                // Download the data to a file.
                client.DownloadFile("http://www.contoso.com", "page.htm");

                // Upload some form post values.
                NameValueCollection form = new NameValueCollection
                {
                    { "MyName", "MyValue" }
                };
                byte[] responseData = client.UploadValues("http://www.contoso.com/form.aspx", form);
            }
            catch (WebException webEx)
            {
                Console.WriteLine(webEx.ToString());
                if (webEx.Status == WebExceptionStatus.ConnectFailure)
                {
                    Console.WriteLine("Are you behind a firewall?  If so, go through the proxy server.");
                }
            }
        }
    }
}

4.生成效果

<html>
    <head>
        <title>Microsoft Corporation</title>
        <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"></meta>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><meta name="SearchTitle" content="Microsoft.com" scheme=""></meta>
        <meta name="Description" content="Get product information, support, and news from Microsoft." scheme=""></meta>
        <meta name="Title" content="Microsoft.com Home Page" scheme=""></meta>
        <meta name="Keywords" content="Microsoft, product, support, help, training, Office, Windows, software, download, trial, preview, demo,  business, security, update, free, computer, PC, server, search, download, install, news" scheme=""></meta>
        <meta name="SearchDescription" content="Microsoft.com Homepage" scheme=""></meta>
    </head>
    <body>
        <p>Your current User-Agent string appears to be from an automated process, if this is incorrect, please click this link:<a href="http://www.microsoft.com/en/us/default.aspx?redir=true">United States English Microsoft Homepage</a></p>
    </body>
</html>

二、HttpClient 类

        命名空间:System.Net.Http。一个用于从 URI 标识的资源发送 HTTP 请求和接收 HTTP 响应的类。

1.示例源码

// HttpClient
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
// Call asynchronous network methods in a try/catch block to handle exceptions.
namespace test1 
{  
    class Program
    {
        static readonly HttpClient client = new();
        static async Task Main()
        {           
            try
            {
                using HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                // Above three lines can be replaced with new helper method below
                // string responseBody = await client.GetStringAsync(uri);

                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }
    }  
}

2.生成效果

// 运行结果 
<html>
    <head>
        <title>Microsoft Corporation</title>
        <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"></meta>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
        <meta name="SearchTitle" content="Microsoft.com" scheme=""></meta>
        <meta name="Description" content="Get product information, support, and news from Microsoft." scheme=""></meta>
        <meta name="Title" content="Microsoft.com Home Page" scheme=""></meta>
        <meta name="Keywords" content="Microsoft, product, support, help, training, Office, Windows, software, download, trial, preview, demo,  business, security, update, free, computer, PC, server, search, download, install, news" scheme=""></meta>
        <meta name="SearchDescription" content="Microsoft.com Homepage" scheme=""></meta>
    </head>
    <body>
        <p>Your current User-Agent string appears to be from an automated process, if this is incorrect, please click this link:<ahref="http://www.microsoft.com/en/us/default.aspx?redir=true">United States English Microsoft Homepage</a></p>
    </body>
</html>

相关推荐

  1. 如何区分ABC网络地址?

    2023-12-07 13:38:02       29 阅读
  2. C++核心编程和对象 笔记

    2023-12-07 13:38:02       46 阅读
  3. [C++提高编程](二):模板--模板

    2023-12-07 13:38:02       48 阅读
  4. C++的设计编程示例

    2023-12-07 13:38:02       34 阅读
  5. C++模板编程—学习C++库的编程基础

    2023-12-07 13:38:02       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-07 13:38:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-07 13:38:02       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-07 13:38:02       87 阅读
  4. Python语言-面向对象

    2023-12-07 13:38:02       96 阅读

热门阅读

  1. nvm,node,npm,yarn相关安装报错问题记录

    2023-12-07 13:38:02       65 阅读
  2. CSS-2

    2023-12-07 13:38:02       47 阅读
  3. 数据库sql是什么?

    2023-12-07 13:38:02       56 阅读
  4. [Swift]RxSwift常见用法详解

    2023-12-07 13:38:02       54 阅读
  5. 开启gitlab中远程连接pgsql

    2023-12-07 13:38:02       47 阅读
  6. 【原创】Mac mini M1安装home-brew

    2023-12-07 13:38:02       56 阅读
  7. AURIX TC芯片中DSU实现安全启动

    2023-12-07 13:38:02       53 阅读
  8. 网络攻击有什么危害,该如何防御

    2023-12-07 13:38:02       58 阅读
  9. Mysql支持ssl

    2023-12-07 13:38:02       49 阅读
  10. docker

    docker

    2023-12-07 13:38:02      45 阅读
  11. uniapp图片预览

    2023-12-07 13:38:02       60 阅读