Webclient

using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            TestWebclient testWebclient = new TestWebclient();
            testWebclient.WebClientUpload();
            //WebClientDownload();
            //WebClientUpload();
            //WebClientDelete();
            Console.ReadKey();
        }

        #region 下载
        /// <summary>
        /// 下载
        /// </summary>
        static void WebClientDownload()
        {
            WebClient webClient = new WebClient
            {
                Credentials = CredentialCache.DefaultCredentials
            };
            //Uri _uri = new Uri(@"http://localhost:8082/123.txt");
            Uri uri = new Uri(@"http://192.168.0.100:8082/123.txt");
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
            webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
            webClient.DownloadFileAsync(uri, @"D:\download\123.txt");
        }

        private static void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Console.WriteLine("下载完成...");
        }

        private static void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Console.WriteLine($"{e.ProgressPercentage}:{e.BytesReceived}/{e.TotalBytesToReceive}");
        }

        #endregion

        #region 上传

        /// <summary>
        /// 上传
        /// </summary>
        static void WebClientUpload()
        {
            WebClient webClient = new WebClient
            {
                Credentials = new NetworkCredential("test", "123")
            };
            Uri uri = new Uri(@"http://192.168.0.100:8082/456.xlsx");
            webClient.UploadProgressChanged += WebClient_UploadProgressChanged;
            webClient.UploadFileCompleted += WebClient_UploadFileCompleted;
            webClient.UploadFileAsync(uri, "PUT", @"D:\download\456.xlsx");
        }

        private static void WebClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            Console.WriteLine("上传完成...");
        }

        private static void WebClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            Console.WriteLine($"{e.ProgressPercentage}:{e.BytesSent}/{e.TotalBytesToSend}");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        static void WebClientDelete()
        {
            WebClient webClient = new WebClient
            {
                Credentials = new NetworkCredential("test", "123")
            };
            Uri uri = new Uri(@"http://192.168.0.100:8082/456.xlsx");           
            webClient.UploadDataCompleted += WebClient_UploadDataCompleted;
            webClient.UploadDataAsync(uri, "DELETE", new byte[0]);
        }

        private static void WebClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            Console.WriteLine("已删除...");
        }
        #endregion
    }

}
 

### WebClient 的基本概念与使用方法 `WebClient` 是 Spring Framework 中用于发起 HTTP 请求的一个重要工具,它是基于反应式编程模型设计的客户端库。它支持异步、非阻塞的操作模式,并且可以很好地集成到响应式的生态系统中。 #### 基本功能概述 `WebClient` 提供了丰富的功能集,包括但不限于配置请求头、设置查询参数、发送 JSON 数据、接收并解析响应数据等功能[^2]。以下是 `WebClient` 的一些核心特性: - **反应式编程支持**:通过 Reactor 库中的 `Mono` 和 `Flux` 类型返回结果,能够轻松处理流式数据。 - **灵活的构建方式**:可以通过链式调用来定义复杂的请求逻辑。 - **强大的自定义能力**:允许开发者自由定制拦截器、过滤器以及其他扩展组件。 下面是一个简单的例子展示如何创建和使用 `WebClient` 实现 GET 请求操作: ```java import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; public class WebClientExample { private static final WebClient webClient = WebClient.builder() .baseUrl("https://jsonplaceholder.typicode.com") // 设置基础 URL 地址 .build(); public static void main(String[] args) { Mono<String> response = webClient.get() // 发起 GET 方法请求 .uri("/posts/1/title") // 配置具体的 URI 路径 .retrieve() // 获取服务器端返回的数据包 .bodyToMono(String.class); // 将接收到的内容转换成字符串形式 response.subscribe(System.out::println); // 输出最终的结果值 } } ``` 上述代码片段展示了怎样利用 `WebClient` 向指定的服务接口发出读取帖子标题的网络访问命令[^3]。注意这里采用了函数式风格编写程序流程,使得整个过程更加简洁明了。 另外,在实际开发过程中可能还需要考虑错误处理机制等问题,这同样也可以借助于 `onStatus`, `onErrorResume` 等钩子来进行优雅管理。 #### 关于为什么不继续沿用 RestTemplate? 尽管 `RestTemplate` 曾经是非常流行的解决方案之一,但它本质上属于同步阻塞性 I/O 模型下的产物;而随着现代应用架构向微服务方向演进,对于高并发场景的需求日益增长,因此官方推荐逐步迁移到更高效的替代品——即我们刚才介绍过的 `WebClient` 上去。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值