在.Net 平台下,建立一個ASP.Net的程式
1、引用兩個NAMESPACE
using System.Text //因為用了Encoding類
using System.Net //因為用了WebClient 類
2、整個程式用了三個控制項
txtUrl //輸入你要擷取的網頁地址 TEXTBOX控制項
txtBody //得到你要擷取的網頁內容 TEXTBOX控制項
btnReturn //按鈕BUTTON控制項
3、在***.aspx.cs下的代碼
private void btnReturn_Click(object sender, System.EventArgs e)
{
string url=txtUrl.Text.Trim(); //擷取輸入的網頁地址
WebClient wb=new WebClient(); //建立一個WebClient執行個體
//擷取或設定用於對向 Internet 資源的請求進行身分識別驗證的網路憑據。(可有可無)
//wb.Credentials=CredentialCache.DefaultCredentials;
//從資源下載資料並返回位元組數組。(加@是因為網址中間有"/"符號)
byte[] pagedata=wb.DownloadData(@url);
//轉換字元、
string result=Encoding.Default.GetString(pagedata);
txtBody.Text=result;
}
4、字***.aspx的HTML代碼中加入一條代碼
在第一行代碼<%@ page=.............................%> 中加入validateRequest=false
總結:整個代碼不過才幾行,而且還不用操心亂碼的事情,我是昨天自己在協助文檔裡偶然看見的,其實WebClient類有很多下載資源和上傳資源的方法,有興趣的朋友可以看看下面有關WebClient類的協助文檔:
WebClient 類請參見
WebClient 成員 | System.Net 命名空間 | WebRequest | WebResponse | HttpWebRequest |
HttpWebResponse | WebClient 成員(Visual J# 文法) | C++ 託管擴充編程
要求
命名空間: System.Net
平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP
Professional, Windows Server 2003 系列
程式集: System (在 System.dll 中)
.NET Framework 安全性:
WebPermission,用於訪問所請求的 URI 或請求被重新導向到的任何 URI。關聯的枚舉:Connect。
語言
C#
C++
JScript
Visual Basic
全部顯示
提供向 URI 標識的資源發送資料和從 URI 標識的資源接收資料的公用方法。不能繼承此類。
有關此類型所有成員的列表,請參閱 WebClient 成員。
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Net.WebClient
[Visual Basic]
<ComVisible(True)>
NotInheritable Public Class WebClient
Inherits Component
[C#]
[ComVisible(true)]
public sealed class WebClient : Component
[C++]
[ComVisible(true)]
public __gc __sealed class WebClient : public Component
[JScript]
public
ComVisible(true)
class WebClient extends Component
安全執行緒
此類型的所有公用靜態(Visual Basic 中為 Shared)成員對多線程操作而言都是安全的。但不保證任何執行個體
成員是安全執行緒的。
備忘
WebClient 類提供向 URI 標識的任何本地、Intranet 或 Internet 資源發送資料以及從這些資源接收資料的
公用方法。
WebClient 類使用 WebRequest 類提供對 Internet 資源的訪問。WebClient 執行個體可以通過任何已向
WebRequest.RegisterPrefix 方法註冊的 WebRequest 子代訪問資料。
注意 預設情況下,.NET Framework 支援以 http:、https: 和 file: 方案標識符開頭的 URI。
WebClient 類提供四種將資料上傳到資源的方法:
OpenWrite 返回一個用於將資料發送到資源的 Stream。
UploadData 將位元組數組發送到資源並返回包含任何響應的位元組數組。
UploadFile 將本地檔案發送到資源並返回包含任何響應的位元組數組。
UploadValues 將 NameValueCollection 發送到資源並返回包含任何響應的位元組數組。
WebClient 類還提供三種從資源下載資料的方法:
DownloadData 從資源下載資料並返回位元組數組。
DownloadFile 從資源將資料下載到本地檔案。
OpenRead 從資源以 Stream 的形式返回資料。
要求
命名空間: System.Net
平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP
Professional, Windows Server 2003 系列
程式集: System (在 System.dll 中)
.NET Framework 安全性:
WebPermission,用於訪問所請求的 URI 或請求被重新導向到的任何 URI。關聯的枚舉:Connect。
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/21aspnet/archive/2007/03/24/1539645.aspx