用C#读取网页
本文地址: document.write(document.URL)
发布于 var path=document.URL;date=path.substring(40,44);month=path.substring(45,47);day=path.substring(48,50);document.write(date+'年'+month+'月'+day+'日');
此文为翻译:
原文地址:http://www.devtopics.com/read-a-web-page-in-c/
在c#中可以很容易的使用system.net.webclient 类来获取一个网页内容:
using
System.Net;
using System.Windows.Forms;
string url = " http://www.devtopics.com " ;
string result = null ;
try
{
WebClientclient = new WebClient();
result = client.DownloadString(url);
}
catch (Exceptionex)
{
// handleerror
MessageBox.Show(ex.Message);
}
using System.Windows.Forms;
string url = " http://www.devtopics.com " ;
string result = null ;
try
{
WebClientclient = new WebClient();
result = client.DownloadString(url);
}
catch (Exceptionex)
{
// handleerror
MessageBox.Show(ex.Message);
}
获取到的网页内容保存到'Result'字符串中。注意:传给DownloadString函数的参数必须是以http://开头,否则它将报一个WebException异常。
另一种方法是使用System.Net.HttpWebRequest 类,它的兼容性更好,因为它直接使用http和服务器通讯。
using
System.Net;
using System.IO;
using System.Windows.Forms;
string result = null ;
string url = " http://www.devtopics.com " ;
WebResponseresponse = null ;
StreamReaderreader = null ;
try
{
HttpWebRequestrequest = (HttpWebRequest)WebRequest.Create(url);
request.Method = " GET " ;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(),Encoding.UTF8);
result = reader.ReadToEnd();
}
catch (Exceptionex)
{
// handleerror
MessageBox.Show(ex.Message);
}
finally
{
if (reader != null )
reader.Close();
if (response != null )
response.Close();
}
using System.IO;
using System.Windows.Forms;
string result = null ;
string url = " http://www.devtopics.com " ;
WebResponseresponse = null ;
StreamReaderreader = null ;
try
{
HttpWebRequestrequest = (HttpWebRequest)WebRequest.Create(url);
request.Method = " GET " ;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(),Encoding.UTF8);
result = reader.ReadToEnd();
}
catch (Exceptionex)
{
// handleerror
MessageBox.Show(ex.Message);
}
finally
{
if (reader != null )
reader.Close();
if (response != null )
response.Close();
}
本文地址: document.write(document.URL)