zoukankan      html  css  js  c++  java
  • 用 WebClient 轻松实现文件下载上传、网页抓取

    我们知道用 WebRequest(HttpWebRequestFtpWebRequest) 和 WebResponse(HttpWebResponse、FtpWebResponse)可以实现文件下载上传、网页抓取,可是用 WebClient 更轻松。

    用 DownloadFile 下载网页

    using (System.Net.WebClient client = new System.Net.WebClient())
    {
        client.DownloadFile("http://www.cftea.com/""C:\\foo.txt");
    }

    就这样,http://www.cftea.com/ 首页就被保存到 C 盘下了。

    用 DownloadData 或 OpenRead 抓取网页

    using (System.Net.WebClient client = new System.Net.WebClient())
    {
        byte[] bytes = client.DownloadData("http://www.cftea.com/");
        string str = (System.Text.Encoding.GetEncoding("gb2312").GetString(bytes);
    }

    我们将抓取来的网页赋给变量 str,任由我们使用。也可以用 OpenRead 方法来获取数据流。

    using (System.Net.WebClient client = new System.Net.WebClient())
    {
        using (System.IO.Stream stream = client.OpenRead("http://www.cftea.com/"))
        {
            using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding("gb2312")))
            {
                string str = reader.ReadToEnd();
                reader.Close();
            }
            stream.Close();
        }
    }

    用 UploadFile 上传文件

    相对于 DownloadData、OpenRead,WebClient 也具有 UploadData、OpenWrite 方法,但最常用的恐怕还是上传文件,也就是用方法 UploadFile。

    using (System.Net.WebClient client = new System.Net.WebClient())
    {
        client.Credentials = new System.Net.NetworkCredential("用户名""密码");
        client.UploadFile("ftp://www.cftea.com/foo.txt""C:\\foo.txt");
    }

    注意 UploadFile 的第一个参数,要把上传后形成的文件名加上去,也就是说这里不能是:ftp://www.cftea.com/。

    用 UploadValues POST 数据

    WebClient wb = new WebClient();
    NameValueCollection nvc = new NameValueCollection();
    nvc.Add("param1", param1);
    nvc.Add("param2", param2);
    wb.UploadValues(url, "post", nvc);
  • 相关阅读:
    将Web项目War包部署到Tomcat服务器基本步骤(完整版)
    性能实战分析-环境搭建(一)
    SQL Server Profiler追踪数据库死锁
    性能测试的各种监控工具大全
    python学习
    Linux常见面试题一
    Linux下用于查看系统当前登录用户信息的4种方法
    HDU 1394 Minimum Inversion Number(线段树求逆序对)
    SGU 180 Inversions(离散化 + 线段树求逆序对)
    Codeforces Round #FF (Div. 2) C. DZY Loves Sequences
  • 原文地址:https://www.cnblogs.com/jordan2009/p/2728888.html
Copyright © 2011-2022 走看看