通过http请求获取指定url的页面
2015-05-27 21:31
344 查看
一、定义类
public class HttpWebResponseUtility { private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; /// <summary> /// 创建GET方式的HTTP请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public static string CreateGetHttpResponse(string url,int? timeout,string userAgent=null,CookieCollection cookies=null) { if(string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.UserAgent = DefaultUserAgent; if(!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if(timeout.HasValue) { request.Timeout = timeout.Value; } if(cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } HttpWebResponse webreponse = request.GetResponse() as HttpWebResponse; try { using(StreamReader reader = new StreamReader(webreponse.GetResponseStream(),System.Text.Encoding.UTF8)) { return reader.ReadToEnd(); } } catch(Exception exp) { return exp.ToString(); } } }
二、调用方式:
HttpWebResponseUtility.CreateGetHttpResponse(url,null);拿到字符串格式的HTML文本就可以写入新的html中。
相关文章推荐
- 通过URL获取html代码实现页面嵌入(代替iframe效果)
- PHP代码:获取指定URL页面中的所有链接
- 通过COM来获取指定url的Cookie(转载)
- 转载: js jquery 获取当前页面的url,获取frameset中指定的页面的url(有修改)
- php通过隐藏表单控件获取到前两个页面的url
- AngularJS 通过 $location 获取与修改当前页面URL
- 通过URL传参数,然后第二个页面需要获取参数
- 获取指定URl页面中所有链接
- JS获取页面通过URL传的参数
- dom4j来解析xml,通过URL获取服务器端返回的字符串,java swing 实现的页面
- PHP 获取指定URl页面中所有链接
- 通过url获取页面信息
- PHP 获取指定URL页面中的所有链接
- Angular 通过注入 $location 获取与修改当前页面URL的实例
- C#通过url获取页面html
- PHP代码:获取指定URL页面中的所有链接
- 日常问题记录--JSP页面中通过<s:property value="#parameters.userName[0]>获取URL参数中文时为乱码的解决办法
- html页面中js获取当前url下指定参数的值
- java通过指定的URL获取图片信息(长宽)
- php通过$_SERVER获取当前页面完整URL地址