WebRequest 后台访问网页内容

1 方法封装: 

 public static class WebFunc
    {

public static string GetHtml(string url, Encoding encoding)
        {
            string html = string.Empty;
            try
            {
                WebRequest request;
                request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Timeout = 20000;
                WebResponse response;
                response = request.GetResponse();
                html = new StreamReader(response.GetResponseStream(), encoding).ReadToEnd();
            }
            catch(System.UriFormatException uex)
            {
                LogHelper.Error(string.Format("ex:{0}, url:{1}", uex, url));
            }
            catch (System.Net.WebException ex)
            {
                LogHelper.Error(string.Format("ex:{0}, url:{1}", ex, url));
            }
            return html;
        }

}

 

调用:  string contents = WebFunc.GetHtml(url,Encoding.GetEncoding("gb2312"));

posted @ 2012-08-08 20:45  沐雪架构师  阅读(216)  评论(0编辑  收藏  举报