1、下载网页源码:

   private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
string toUrl = Application.StartupPath + "\\" + Path.GetFileName(url); WebClient wc = new WebClient();
wc.DownloadDataAsync(new Uri(url));
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
} void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error == null && e.Cancelled == false)
textBox2.Text = Encoding.UTF8.GetString(e.Result);
else
MessageBox.Show(e.Error.Message);
}

2、直接下载文件,比较简单,但下载比较伤硬盘:

        private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
string toUrl = Application.StartupPath + "\\" + Path.GetFileName(url); WebClient wc = new WebClient();
wc.DownloadFileCompleted += wc_DownloadFileCompleted;
wc.DownloadFileAsync(new Uri(url), toUrl);
} void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("下载完成");
}

3、利用缓存下载文件,可以更好的保护硬盘

private void button2_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.OpenReadAsync(new Uri(textBox1.Text));
wc.OpenReadCompleted += wc_OpenReadCompleted;
}
async void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
await SaveFile(e.Result, Application.StartupPath + "\\" + Path.GetFileName(textBox1.Text));
MessageBox.Show("下载完成");
}
else
{
MessageBox.Show(e.Error.Message);
}
}
Task SaveFile(Stream stream, string savepath)
{
return Task.Run(() =>
{
var read = stream;
byte[] buf = new byte[];
int res = ;
FileStream fs = File.Open(savepath, FileMode.OpenOrCreate);
using (fs)
{
while ((res = read.Read(buf, , buf.Length)) > )
{
fs.Write(buf, , res);
fs.Flush();
}
}
read.Close();
read.Dispose();
});
}

4、上传文件

web网站创建一般处理程序  FileHandler:

public class FileHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
HttpFileCollection files = context.Request.Files;
if (files.Count > )
{
files[].SaveAs(HttpContext.Current.Server.MapPath("files/" + context.Request.QueryString["fname"]));
context.Response.Write("save success!");
}
else
context.Response.Write("hello request!");
}
catch (Exception ex)
{
context.Response.Write("save error!" + ex.Message);
}
} public bool IsReusable
{
get
{
return false;
}
}
}

由于网站对上传文件大小有限制,修改上传大小可以在ASP.Net在web.config中设置:

<system.web>
<httpRuntime maxRequestLength="" //即40MB,1KB=1024
useFullyQualifiedRedirectUrl="true"
executionTimeout=""
minFreeThreads=""
minLocalRequestFreeThreads=""
appRequestQueueLimit=""
enableVersionHeader="true"
/>
</system.web>

对于webclient,在winform窗体上点击按钮,则把文件上传到上面的服务器网站目录中。

        private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{ string path = openFileDialog1.FileName;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.QueryString["fname"] = openFileDialog1.SafeFileName;
byte[] fileb = wc.UploadFile(new Uri(@"http://localhost:15993/FileHandler.ashx"), "POST", path);
string res = Encoding.UTF8.GetString(fileb);
MessageBox.Show(res);
}
}

5、向服务器发送文字

服务器Test.ashx:

 public class Test : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; int len=context.Request.ContentLength;
var buf=context.Request.BinaryRead(len);
var res=Encoding.UTF8.GetString(buf); context.Response.Write("Result="+res);
} public bool IsReusable
{
get
{
return false;
}
}
}

客户机:

        private void button2_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
var data = textBox2.Text; wc.UploadStringAsync(new Uri("http://localhost:15993/Test.ashx"), "POST", data);
wc.UploadStringCompleted += wc_UploadStringCompleted;
} void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}

6、上传表单

服务器端用.net  Controller:

 public ActionResult add(int a,int b)
{
int c = a + b;
return Content(c.ToString()); ;
}

客户机:

        private void button3_Click(object sender, EventArgs e)
{
var data = "a=1&b=2";
var postData = Encoding.UTF8.GetBytes(data); WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UploadDataAsync(new Uri("http://localhost:15993/home/add"), "POST", postData);
wc.UploadDataCompleted += wc_UploadDataCompleted;
} void wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
MessageBox.Show(Encoding.UTF8.GetString( e.Result,,e.Result.Length));
}

WebClient的使用的更多相关文章

  1. 跨域请求——WebClient通过get和post请求api

    AJAX不可以实现跨域请求,经过特殊处理才行.一般后台可以通过WebClient实现跨域请求~ //get 请求        string url = string.Format("htt ...

  2. C#通过WebClient/HttpWebRequest实现http的post/get方法

    C#通过WebClient/HttpWebRequest实现http的post/get方法 http://www.cnblogs.com/shadowtale/p/3372735.html

  3. WebClient 实现多文件/文本同时上传

    public class CreateBytes { Encoding encoding = Encoding.UTF8; /**/ /// <summary> /// 拼接所有的二进制数 ...

  4. WebClient 数据传输

    数据提交 post  ,get public string WebClientPost(string PostData, string PostUrl, string Type) { string p ...

  5. C# 文件下载 : WebClient

    最近更新了一个下载小工具,主要提升了下面几点: 1. 在一些分公司的局域网中,连接不上外网 2. 服务器上的文件更新后,下载到的还是更新前的文件 3. 没有下载进度提示 4. 不能终止下载 下面和大家 ...

  6. C# 发送Http请求 - WebClient类

    WebClient位于System.Net命名空间下,通过这个类可以方便的创建Http请求并获取返回内容. 一.用法1 - DownloadData string uri = "http:/ ...

  7. c# WebClient Get Post 方法

    public string GetData(string url) { string data; using (var client = new WebClient()) { using (var s ...

  8. c# WebClient文件下载

    public void HttpDownload(string url, string path, ResourceType type) { using (var client = new WebCl ...

  9. [解决WebClient或HttpWebRequest首次连接缓慢问题]

    [编程环境]Visual Studio 2010, NET4.0 [开发语言]C#, 理论上VB.NET等依赖.NET Framework框架的语言均受此影响 [问题描述] 使用HttpWebRequ ...

  10. winform客户端利用webClient实现与Web服务端的数据传输

    由于项目需要,最近研究了下WebClient的数据传输.关于WebClient介绍网上有很多详细介绍,大概就是利用WebClient可以实现对Internet资源的访问.无外乎客户端发送请求,服务端处 ...

随机推荐

  1. 20155209实验二《Java面向对象程序设计》

    20155209实验二<Java面向对象程序设计> 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计 ...

  2. 20155239《Java程序设计》实验一(Java开发环境的熟悉)实验报告

    实验内容及步骤 使用JDK编译.运行简单的java程序 2.使用IDEA编辑.编译.运行.调试Java程序 (一)使用JDK编译.运行简单的java程序 命令行下的程序开发 先建立一个文件夹命名为Co ...

  3. 2017-2018-1 20155319《信息安全技术》实验二——Windows口令破解

    2017-2018-1 20155319<信息安全技术>实验二--Windows口令破解 实验环境 试验系统:Windows 2003 实验工具:LC5.SuperDic 实验原理 一.口 ...

  4. # 20155337 《Android程序设计》实验四实验报告

    20155337 <Android程序设计>实验四实验报告 实验一 实验内容 Android Stuidio的安装测试: 参考<Java和Android开发学习指南(第二版)(EPU ...

  5. 20145209 实验一《Java开发环境的熟悉》实验报告

    20145209 实验一<Java开发环境的熟悉>实验报告 实验内容 1.使用JDK编译.运行简单的Java程序. 2.使用Eclipse 编辑.编译.运行.调试Java程序. 提交 Li ...

  6. jenkins+jacoco+ant自动化代码和应用服务代码分离场景获取远程服务的覆盖率

    前提 自动化代码和应用服务代码分离.jenkins和tomcat服务器分离 思想 1.在tomcat启动javaagent监听. 2.运用其他job_B已部署的应用服务代码 3.拉取自动化代码,开始测 ...

  7. ubuntu apt-xxx

    1. apt-get install xxx 2. dpkg -l ; list software already installed. 3. apt-cache dumpavail ; print ...

  8. centos7 python2.7.5 升级python3.6.4

    (转)Linux Centos7 升级python2至python3 - 依然范儿特西的文章 - 知乎 https://zhuanlan.zhihu.com/p/33660059 1 查看python ...

  9. 【CentOS】安装Docker教程

    前提条件 Docker 运行在 CentOS 7 上,要求系统为64位.系统内核版本为 3.10 以上. Docker 运行在 CentOS-6.5 或更高的版本的 CentOS 上,要求系统为64位 ...

  10. Zookeeper-----Zookeeper概述

    一:Zookeeper的概念? ZooKeeper是一种分布式协调服务,用于管理大型主机.在分布式环境中协调和管理服务是一个复杂的过程.ZooKeeper通过其简单的架构和API解决了这个问题.Zoo ...