现在的位置: 首页 > 综合 > 正文

HttpWebRequest

2011年08月01日 ⁄ 综合 ⁄ 共 2406字 ⁄ 字号 评论关闭
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;

namespace Test
{
    
/// <summary>
    
/// WebForm1 的摘要说明。
    
/// </summary>

    public class WebForm1 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.TextBox txtUrl;
        
protected System.Web.UI.WebControls.Button btnGet;
        
protected System.Web.UI.WebControls.TextBox txtResult;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
        }


        
public   static   string   getHtmlContent(string   url)   
        
{   
            
string resultStr = string.Empty;   
            System.Net.HttpWebRequest hreq 
= null;   
            System.Net.HttpWebResponse hrep   
= null;   
            Stream stream 
= null;   
            StreamReader sReader 
= null;   
            
try   
            
{   
                hreq 
= (HttpWebRequest)WebRequest.Create(url);   
                hreq.
                hreq.Timeout
=10000;   
                hrep 
= (HttpWebResponse)hreq.GetResponse();   
                stream 
= hrep.GetResponseStream();   
                sReader 
= new StreamReader(stream,System.Text.Encoding.Default);   
                resultStr 
= sReader.ReadToEnd();   
            }
   
            
finally   
            
{   
                sReader.Close();   
                stream.Close();   
                hrep.Close();   
            }
   
            
return   resultStr;   
    
        }

        
        
Web 窗体设计器生成的代码

        
private void btnGet_Click(object sender, System.EventArgs e)
        
{
            
string strUrl=txtUrl.Text;
            txtResult.Text
=getHtmlContent(strUrl);
        }

    }

}

抱歉!评论已关闭.