海纳百川 有容乃大(http://www.brtech.com.cn)

海纳百川,有容乃大(http://www.brtech.com.cn)

  :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

公告

 

public class SampleCode

{

          
public SampleCode()

          
{}

          

          
//       Download the HTML source code at the specified URL

          
//       You can optionally specify the username/password credentials,

          
//       in case the page uses Basic Authentication

          
//       Returns a null string if any error occurs

 

          
public static string GetHtmlPageSource(string url)

          
{

               
return GetHtmlPageSource(url, nullnull);

          }


          

          
public static string GetHtmlPageSource(string url, string username, string password)

          
{

              System.IO.Stream st 
= null;

          System.IO.StreamReader sr 
= null;

 

              
try

              
{

                  
// make a Web request

                  System.Net.WebRequest req 
= System.Net.WebRequest.Create(url);

                  

                             
// if the username/password are specified, use these credentials

                  
if( username != null && password != null )

                    req.Credentials 
= new System.Net.NetworkCredential(username, password);

                  

                  
// get the response and read from the result stream

                  System.Net.WebResponse resp 
= req.GetResponse();

                  st 
= resp.GetResponseStream();

                  sr 
= new System.IO.StreamReader(st);

                             

                  
// read all the text in it

                  
return sr.ReadToEnd();

              }


              
catch(Exception ex)

              
{

                    
return string.Empty;

              }


              
finally

              
{

                  
// always close readers and streams

                  sr.Close();

                  st.Close();

              }


          }


}


posted on 2006-03-27 13:28 阿昆 阅读(...) 评论(...) 编辑 收藏