C#语言之HttpWebRequest与HttpWebResponse获取网页内容

HttpWebRequest类对WebRequest中定义的属性和方法提供支持,使用System.Net.WebRequest.Create(URI uriString)来创建实例,返回的是HttpWebRequest对象。GetResponse方法向RequestUri属性指定的资源发出同步请求并返回包含该响应的HttpWebResponse。

下面示例代码来源于微软MSDN官网,绝对经典!

public static byte[] GetURLContents(string url)
{
    // The downloaded resource ends up in the variable named content.
    var content = new MemoryStream();
    // Initialize an HttpWebRequest for the current URL.
    var webReq = (HttpWebRequest)WebRequest.Create(url);
    // Send the request to the Internet resource and wait for
    // the response.
    // Note: you can't use HttpWebRequest.GetResponse in a Windows Store app.
    using (WebResponse response = webReq.GetResponse())
    {
        // Get the data stream that is associated with the specified URL.
        using (Stream responseStream = response.GetResponseStream())
        {
            // Read the bytes in responseStream and copy them to content.
            responseStream.CopyTo(content);
        }
    }
    // Return the result as a byte array.
    return content.ToArray();
}

Leave a Reply

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