本文主要是介绍C#获取指定网页HTML原代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C#获取指定网页HTML原代码可使用 WebClient WebRequest HttpWebRequest 三种方式来实现。
WebClient
private string GetWebClient( string url) { string strHTML = "" ; WebClient myWebClient = new WebClient(); Stream myStream = myWebClient.OpenRead(url); StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding( "utf-8" )); strHTML = sr.ReadToEnd(); myStream.Close(); return strHTML; } |
WebRequest
private string GetWebRequest( string url) { Uri uri = new Uri(url); WebRequest myReq = WebRequest.Create(uri); WebResponse result = myReq.GetResponse(); Stream receviceStream = result.GetResponseStream(); StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding( "utf-8" )); string strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return strHTML; } |
HttpWebRequest
private
string
GetHttpWebRequest(
string
url)
{
Uri uri =
new
Uri(url);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
myReq.UserAgent =
"User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"
;
myReq.Accept =
"*/*"
;
myReq.KeepAlive =
true
;
myReq.Headers.Add(
"Accept-Language"
,
"zh-cn,en-us;q=0.5"
);
HttpWebResponse result = (HttpWebResponse)myReq.GetResponse();
Stream receviceStream = result.GetResponseStream();
StreamReader readerOfStream =
new
StreamReader(receviceStream, System.Text.Encoding.GetEncoding(
"utf-8"
));
string
strHTML = readerOfStream.ReadToEnd();
readerOfStream.Close();
receviceStream.Close();
result.Close();
return
strHTML;
}
这篇关于C#获取指定网页HTML原代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!