C#语言程序设计之WebClient获取网页内容

WebClient类提供用于向由URI标识的任何本地、intranet或Internet资源发送数据或从其接收数据的常用方法。WebClient类使用WebRequest类提供对资源的访问权限。WebClient实例可以使用通过方法注册的任何子代来访问数据WebRequest WebRequest.RegisterPrefix。

public static byte[] GetURLContents(string url)
{
    MemoryStream content = new MemoryStream();
    string ua = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0";

    WebClient client = new WebClient();
    client.Headers.Add("user-agent", ua);

    using (Stream stream = client.OpenRead(url))
    {
        stream.CopyTo(content);
    }

    return content.ToArray();
}

Leave a Reply

Your email address will not be published. Required fields are marked *