C# 对于WebClient学习我们会吗?

2,390 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

前言:

今天我们一起学习一下关于使用WebClit实现上传下载,WebClit是一个高层类使用简单,还支持异步,WebClient比WebRequest比HttpWebRequest更加简单,它相当于封装了request和response方法,非常的方便我们使用,今天这篇文章我们一起来学习一下吧,创作不易,大家顺便点点赞吧,你的点赞收藏关注,是我写文章的动力,栓Q啦。

12354689123110.gif

WebClient概念

System.Net.WebClient属于高层类、使用简单。均支持异步版本。支持http,https,fpt,files等URI。 命名空间是System.Net,WebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。注意:建议不要将 WebClient 类用于新的开发。Net4.5及以上请改用 System.Net.Http.HttpClient 类。 C# (4).png

WebClient下载操作

OpenRead:打开一个可读的Stream。 对于FTP资源,默认使用RETR命令;对于HTTP资源,默认使用Get方法。

Stream= client.OpenRead(serverUri):

简单示例

WebClient client = new WebClient();
client.Headers.Add("user-agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Encoding = Encoding.GetEncoding("gb2312");
client.Credentials = new NetworkCredential("csp""welcome");

Stream data = client.OpenRead(url);//OpenRead为下载的数据打开一个只读的流
StreamReader reader = new StreamReader(data, Encoding.GetEncoding("gb2312"));
sting s = reader.ReadToEnd();
reader.Close();
return s;

下载操作

1. DownloadData:以byte[]形式下载资源。
byte[] data= client.DownloadData(serverUri):
2. DownloadFile:将资源下载在本地文件。
void client.DownloadFile(serverUri,localFile):
3. DownloadString:以string的形式下载资源。
string content =client.DownloadString(serverUri):
  1. WebClient事件
  • DownloadProgressChanged事件:
  • DownloadCompleted事件
  1. 获取下载网址的真实文件名

获取http头部信息的内容。 Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。 Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,文件直接在浏览器上显示或者在访问时弹出文件下载对话框。形如:”Content-Disposition: attachment;filename=FileName.txt“。当你在响应类型为application/octet- stream情况下使用了这个头信息的话,那就意味着你不想直接显示内容,而是弹出一个"文件下载"的对话框

WebClient client = new WebClient();
byte[] data = client.DownloadData(fileUrl);
var mc = Regex.Matches(
            Server.UrlDecode(client.ResponseHeaders["Content-Disposition"]),
            @"filename=(.+)"
            );
string filename = mc[0].Groups[1].Value;

WebClient上传操作

OpenWrite:打开一个可写的流。对于FTP资源,默认使用STOR命令;对于HTTP资源,默认使用POST方法。

Strean =client.OpenWrite(serverUri);
UploadData:将byte[]数据上传到serverUri。
byte[] =client.UploadData(serverUri,byte[]);
UploadFile:将本地文件上传到serverUri。
byte[] =client.UploadFile(serverUri,localFile);

举例:

WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Credentials = new NetworkCredential("csp""welcome");
client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCompletedCallback);

client.UploadFileAsync(new Uri(uriString + Path.GetFileName(localfileName)), null, localfileName, progressbarfrom);
/// 上传过程处理
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
    (e.UserState as ProgressBar).Value = e.ProgressPercentage;
}

private static void UploadFileCompletedCallback(object sender, UploadFileCompletedEventArgs e)
{
    if (e.Error == null)
        MessageBox.Show("完成上传");
    else
        throw e.Error;
}

UploadValues:将指定的名/值集合到serverUri。

byte[] =client.UploadValues(serverUri,namevalueCollection);

事件:

  • UploadProgressChanged:e.ProcessPercentage,e.TatalBytesToReceive,e.BytesReceived;
  • Upload***Completed: e.Cancelled,e.Error,E.UserState;

四、System.Url类(统一资源表示符)

Uri url=new Uri(”//www.JUEJIN.COM”);
OriginalString 获取传递给 Uri 构造函数的原始 URI 字符串。
Scheme 获取此 URI 的方案名称。http
IsFile 获取一个值,该值指示指定的 Uri 是否为文件 URIfalse
Host 获取此实例的主机部分。www.yisu.com
HostNameType 获取 URI 中指定的主机名的类型。
Port 获取此 URI 的端口号。2105
IsDefaultPort 获取一个值,该值指示 URI 的端口值是否为此方案的默认值。false
AbsolutePath 获取 URI 的绝对路径。/article/247999.htm
Query 获取指定 URI 中包括的任何查询信息。?order=true
PathAndQuery 获取用问号 (?) 分隔的 AbsolutePathQuery 属性。/article/247999.htm?order=true

总结:

这篇文章比较简单,只是简单的学习一下,对它有更多的认识,在有需求的时候最起码有路子,虽然很简单,但是也是可以学到东西的,我们学习了新的知识,对我们的知识储备及技术又有新的一点点的进步,C#的技术就是先简单再难嘛,积少成多之后才会成长才会进步,我们要不断的学习不断的探索,才能有学习的动力,才会有学习的欲望,东西不多,但是实用性挺强建议收藏一下,哈哈哈哈,如果你觉得这篇文章对你有用,点赞最实在,创作不易,点赞评论收藏关注,嘿嘿,不喜勿喷!!!!

12354689