Get data from specified URI using WebRequest and WebResponse(读取网页数据并存入对应html文档)...

  WebRequest is a request to send messages to a URI to send messages, URI as a parameter is passed to Create () method. And we take WebResponse class as data obtained from the server. The method WebRequest.GetResponse () will indeed send the request to the Web server, create a Response object,  and then check the returned data. Like the WebClient object, you can get a stream of data, however, the data flow is obtained by WebResponse.GetResponseStream () method.

  Here is a smple to show you how to get data from URI and save as a html file:

ContractedBlock.gif ExpandedBlockStart.gif Get Data From Uri
ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
/// Get data from url and save as html file.
/// </summary>
/// <param name="uri">The uri where you want to get data from</param>
/// <param name="htmlFile">File used to save data</param>

public static void GetDataFromUri(string uri, string htmlFile)
ExpandedBlockStart.gifContractedBlock.gif
{
    
//Makes a request to specified URI.
    System.Net.WebRequest request = WebRequest.Create(uri);
    System.Net.WebResponse webResponse 
= request.GetResponse();

    
//Initialize a new instance of the System.IO.StreamReader class for the web response stream,
    
//with the specified character encoding, and get all data.
    StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.Default);
    
string dataBuffer = sr.ReadToEnd();

    FileStream output 
= new FileStream(htmlFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
    
byte[] recvBuffer = System.Text.Encoding.Default.GetBytes(dataBuffer);
    BinaryWriter bw 
= new BinaryWriter(output);
    bw.Write(recvBuffer);

    
//If we use this method to write data, some characters will be garbled.
    
//StreamWriter sw = new StreamWriter(output);
    
//sw.Write(dataBuffer);
}

  

  Note this: If we use StreamWriter to write directly, we will get some garbled characters in the html file. Of course that's the encoding problem.

 

Go to my home page for more posts

转载于:https://www.cnblogs.com/lantionzy/archive/2009/10/30/1593250.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值