目录

一、WebClient 类

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

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

3.示例源码

4.生成效果

二、HttpClient 类

1.示例源码

2.生成效果


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

        SYSLIB0014 警告 - .NET | Microsoft Learn

        从 .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 将数据上传到资源的方法

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

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>
12-04 07:37