WebClient的一些简单应用

来源:互联网 发布:定制家具生产软件 编辑:程序博客网 时间:2024/05/22 15:18

      话不多说了,因为要项目加入移动无线城市的头和尾,只能用这个方法.

     

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Net;using System.IO;using System.Text;namespace WebTest{    public partial class WebClientTest : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //下载图片用            //string Url = "http://wap.hljwxcs.com/mycity/skin/revision/wap/default/default/320/images/logo.gif";            //对于文件的读和下载数据用            //string Url = "http://wap.hljwxcs.com/include/header.do";            //下载音频文件用            //string Url = "http://zhangmenshiting.baidu.com/data2/music/1575880/15758731352678461.mp3?xcode=aa8b40c67742d453577895e58b3b93ef";            //测试写操作,如:openWrite            //string Url = "http://localhost/aa.txt";            //测试文件上传用,此文件为接收文件,必写,否则上传无法接收            string Url = "http://localhost/uploadFile.aspx";            OperUploadFileAsync(Url);        }        /// <summary>        /// DownloadData同步下载数据        /// </summary>        /// <param name="Url"></param>        public void OperaDownloadData(string Url)        {            WebClient _client = new WebClient();            //DownloadData的使用方法            byte[] mybyte = _client.DownloadData(new Uri(Url, UriKind.RelativeOrAbsolute));            string stream = System.Text.Encoding.UTF8.GetString(mybyte);            Response.Write(mybyte.Length + "----");            Response.Write(stream);        }        /// <summary>        /// DownloadDataAsync异步下载数据        /// </summary>        /// <param name="Url"></param>        public void OperaDownloadDataAsync(string Url)        {            WebClient _client = new WebClient();            //DownloadDataAsync是DownloadData的异步操作            _client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCallback);            _client.DownloadDataAsync(new Uri(Url, UriKind.Absolute));        }        //DownloadDataAsync异步操作        public void DownloadDataCallback(object sender,DownloadDataCompletedEventArgs e)        {            if (e.Result.Length > 0 && e.Error==null && e.Cancelled==false)            {                this.Label1.Visible = false;                Response.Write(System.Text.Encoding.UTF8.GetString(e.Result));                          }        }        /// <summary>        /// DownloadString下载数据        /// </summary>        /// <param name="Url"></param>        public void OperDownloadString(string Url)        {            WebClient _client = new WebClient();            string Tempstr = _client.DownloadString(Url);            Tempstr = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Default.GetBytes(Tempstr));            Response.Write(Tempstr);        }        /// <summary>        /// DownloadStringAsync异步下载数据        /// </summary>        /// <param name="Url"></param>        public void OperDownloadStringAsync(string Url)        {            WebClient _client = new WebClient();            _client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);            _client.DownloadStringAsync(new Uri(Url, UriKind.RelativeOrAbsolute));        }        /// <summary>        /// DownloadStringAsync异步下载数据--完成方法        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        public void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)        {            //throw new NotImplementedException();            if (e.Result.Length > 0 && e.Error == null && e.Cancelled == false)            {                Response.Clear();                this.Label1.Visible = false;                Response.Write(e.Result);            }        }        /// <summary>        /// DownloadFile下载文件        /// 此处可以下载图片        /// 如果想下载大的文件,音频或是视频,可以使用此方法的异步.因为同步页面停留时间太长        /// </summary>        /// <param name="Url"></param>        public void OperDownloadFile(string Url)        {            WebClient _client = new WebClient();            //下载之后的文件名字            string Path = Server.MapPath("1.mp3");            _client.DownloadFile(Url, Path);        }        /// <summary>        /// DownloadFileAsync异步下载文件,下载时间还是很长        /// 会出现报401错误的,这个需要你去设置IIS的权限了        /// </summary>        /// <param name="Url"></param>        public void OperDownloadFileAsync(string Url)        {            WebClient _client = new WebClient();            string Path = Server.MapPath("1.mp3");            _client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(DownloadFileCompleted);            _client.DownloadFileAsync(new Uri(Url, UriKind.RelativeOrAbsolute), Path);        }        /// <summary>        /// 完成异步下载文件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        public void DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)        {            //throw new NotImplementedException();            if (e.Error == null && e.Cancelled == false)            {                this.Label1.Text = "下载成功!";            }            else            {                this.Label1.Text = "下载失败,原因:" + e.Error.Message;                             }        }        /// <summary>        /// OpenRead读取页面,它的功能与DownloadData相似,都是抓取页面信息.没看出有什么不同.        /// 难道说不同的是一个取回的是字节,一个是数据流吗???        /// </summary>        /// <param name="Url"></param>        public void OperOpenRead(string Url)        {            WebClient _client = new WebClient();            Stream stream = _client.OpenRead(Url);            StreamReader sr = new StreamReader(stream);            Response.Write(sr.ReadToEnd());        }        /// <summary>        /// OpenWriteAsync异步读取页面.功能同上        /// </summary>        /// <param name="Url"></param>        public void OperOpenReadAsync(string Url)        {            WebClient _client = new WebClient();            _client.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCompleted);            _client.OpenReadAsync(new Uri(Url));        }        /// <summary>        /// 异步操作结果        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        public void OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)        {            //throw new NotImplementedException();            if (e.Error == null  && e.Cancelled == false)            {                Stream stream = e.Result;                StreamReader sr = new StreamReader(stream);                Response.Write(sr.ReadToEnd());            }        }        /// <summary>        /// 对URI的文件进写操作,一般来说都不好用,会报远程服务器返回错误: (405) 不允许的方法        /// 因为现在的网站管理员不会把IIS的权限开得太大.个人感觉这个功能,没有什么用        /// 它有几个重载的方法,后面跟的一个string主要是让你来选择是post方式还是put方式进行写        /// </summary>        /// <param name="Url"></param>        public void OperOpenWrite(string Url)        {            WebClient _client = new WebClient();            byte[] postArray = System.Text.Encoding.UTF8.GetBytes("这是能显示出来吗!");            Stream stream = _client.OpenWrite(Url,"PUT");            stream.Write(postArray, 0, postArray.Length);            stream.Close();                    }        /// <summary>        /// 同上,写操作的异步方法        /// </summary>        /// <param name="Url"></param>        public void OperOpenWriteAsync(string Url)        {            WebClient _client = new WebClient();            _client.OpenWriteCompleted += new OpenWriteCompletedEventHandler(OpenWriteCompleted);            _client.OpenWriteAsync(new Uri(Url));        }        /// <summary>        /// 异步完成操作        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        public void OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)        {            //throw new NotImplementedException();            byte[] postArray = System.Text.Encoding.UTF8.GetBytes("这是能显示出来吗!");            Stream stream = e.Result;            stream.Write(postArray, 0, postArray.Length);            stream.Close();          }        /// <summary>        /// 上传数据,此方法可以有二个功能,一个是上传一些数据还有一个就是可以上传图片或是文本        /// 这个例子是上传一个字符串数据,这种方法,在很多情况下用来做自动提交用.        /// </summary>        /// <param name="Url"></param>        public void OperUploadData(string Url)        {            WebClient _client = new WebClient();            string postData = "Username=admin&Password=admin";            // 注意这种拼字符串的ContentType             _client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");            // 转化成二进制数组             byte[] byteArray = Encoding.ASCII.GetBytes(postData);            // 上传数据,并获取返回的二进制数据.             byte[] responseArray = _client.UploadData(Url, "POST", byteArray);          }        /// <summary>        /// 此方法与上面一样,这里只是做了一个图片上传的功能        /// 你需要设置IIS等,不然会报405错误.我一直没调试成功        /// </summary>        /// <param name="Url"></param>        /// <param name="FileName"></param>        public void OperUploadData(string Url, string FileName)        {            WebClient _client = new WebClient();            byte[] postByte = File.ReadAllBytes(@"E:\a.jpg");            _client.UploadData(Url, postByte);        }        /// <summary>        /// 异步上传数        /// </summary>        /// <param name="Url"></param>        public void OperUploadDataAsync(string Url)        {            WebClient _client = new WebClient();            _client.UploadDataCompleted += new UploadDataCompletedEventHandler(UploadDataCompleted);            byte[] postByte = File.ReadAllBytes(@"E:\a.jpg");            _client.UploadDataAsync(new Uri(Url), postByte);        }        /// <summary>        /// 完成异步的方法        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        public void UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)        {            //throw new NotImplementedException();            if (e.Error == null && e.Cancelled == false)            {                Response.Write(System.Text.Encoding.UTF8.GetString(e.Result));            }        }        /// <summary>        /// 文件上传方法,此方法需要一个配套的页面,才能正常下载,URL的地址你要指向这个配套的页面        /// </summary>        /// <param name="Url"></param>        public void OperUploadFile(string Url)        {            WebClient _client = new WebClient();            string FileName = @"E:\1.jpg";            _client.UploadFile(Url,FileName);        }        /// <summary>        /// 异步操作文件上传        /// </summary>        /// <param name="Url"></param>        public void OperUploadFileAsync(string Url)        {            WebClient _client = new WebClient();            _client.UploadFileCompleted += new UploadFileCompletedEventHandler(_client_UploadFileCompleted);            string FileName = @"E:\1.jpg";            _client.UploadFileAsync(new Uri(Url), FileName);        }        void _client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)        {            //throw new NotImplementedException();            if (e.Error == null && e.Cancelled == false)            {                Response.Write("上传完成");            }        }            }}

下面是给出的uploadFile.aspx文件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="uploadFile.aspx.cs" Inherits="WebTest.uploadFile" %><%@ Import Namespace="System"%><%@ Import Namespace="System.IO"%><%@ Import Namespace="System.Net"%><%@ Import NameSpace="System.Web"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><Script language="C#" runat="server">void Page_Load(object sender, EventArgs e) {foreach(string f in Request.Files.AllKeys) {HttpPostedFile file = Request.Files[f];        file.SaveAs(Server.MapPath("/" + file.FileName));}}</Script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title></title>    </head><body>    <form id="form1" runat="server">    <div>        </div>    </form></body></html>