如题,想获取网页的“源代码”,用这个方法
public String GetPageCode(String PageURL, String Charset)
{
try
{
String strHtml = "";
HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(PageURL);
CookieContainer cookieCon = new CookieContainer();
wreq.CookieContainer = cookieCon;
HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
Stream s = wresp.GetResponseStream();
StreamReader objReader = new StreamReader(s, System.Text.Encoding.GetEncoding(Charset));
string strLine = "";
while (strLine != null)
{
strLine = objReader.ReadLine();
if (strLine != null)
{
strHtml += strLine.Trim();
}
}
strHtml = strHtml.Replace("<br />", "\r\n");
return strHtml;
}
catch (Exception n)
{
return n.Message;
}
}
传入的网址,是正确的,但总提示:无法连接远程服务器,请问怎么解决,谢谢了
------解决方案--------------------------------------------------------
- C# code
/// <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 HttpWebResponse CreateGetHttpResponse(string url,int? timeout, string userAgent,CookieCollection cookies) { 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); } return request.GetResponse() as HttpWebResponse; }