用C#读取网页(Read a Web Page in C#)

用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);
}

获取到的网页内容保存到'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();
}
本文地址: document.write(document.URL)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值