c#抓取網頁分析

c#抓取網頁分析

目的:
抓取網頁,分析網頁內容,進行處理獲取信息。
例子:
抓km169上的adsl用戶的費用信息,分析存儲到本地數據庫。
步驟:1、抓取。2、分析。3、存儲。

王暴徒 2006-2-13 05:48
1抓取

        public string GetPage(string url, string postData, out string err)
        {
            err = "";
                        
            Stream outstream = null;

            Stream instream = null;

            StreamReader sr = null;

            HttpWebResponse response = null;

            HttpWebRequest request = null;

            Encoding encoding = Encoding.Default;

            byte[] data = encoding.GetBytes(postData);

            // 準備請求...

            try
            {

                // 設置參數

                request = WebRequest.Create(url) as HttpWebRequest;

                CookieContainer cookieContainer = new CookieContainer();

                request.CookieContainer = cookieContainer;

                request.AllowAutoRedirect = true;

                request.Method = "POST";

                request.ContentType = "application/x-www-form-urlencoded";

                request.ContentLength = data.Length;

                outstream = request.GetRequestStream();

                outstream.Write(data, 0, data.Length);

                outstream.Close();

                //發送請求並獲取相應迴應數據

                response = request.GetResponse() as HttpWebResponse;

                //直到request.GetResponse()程序纔開始向目標網頁發送Post請求

                instream = response.GetResponseStream();

                sr = new StreamReader(instream, encoding);

                //返回結果網頁(html)代碼

                string content = sr.ReadToEnd();

                err = string.Empty;

                return content;

            }

            catch (Exception ex)
            {

                err = ex.Message;

                return string.Empty;

            }

        }

[[i] Last edited by 王暴徒 on 2006-2-13 at 13:49 [/i]]

王暴徒 2006-2-13 05:56
2、分析
        public string Get()
        {
            string str = GetPage(KMADSLURL, strReq, out err);

            Regex rgx = new Regex("table_det//(//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/",//n*//s*/"([^/"]*)/"//);", RegexOptions.Singleline);
            foreach (Match m in rgx.Matches(str))
            {

                Rec r = new Rec();
                r.str1 = m.Groups[1].Value;
                r.Save();
            }
            return null;
        }


此處的關鍵在於正則表達式,利用匹配關係獲得一條條記錄,再用%1~%9分組,得到每個字段的內容,最後生成相應的記錄即可(拼sql也可),這裏用了個持久化的咚咚,下次詳細說。

正則技巧:用^(間隔符號)來劃分字段,:)不大好解釋,大家自己體會下吧。

[[i] Last edited by 王暴徒 on 2006-2-13 at 13:58 [/i]]

Timothy 2006-2-14 01:44

我以前寫了個多線程批量下載歌曲的程序,當時程序考慮的是掛接百渡,同時又預留了擴展性,比如通過配置也可以獲取雅虎的歌曲,這就好考慮到個網站網頁的編碼方式,和暴徒的一樣,我也是用了HttpWebResponse 類.通過對各種編碼的網頁在2進制下面的觀察,發現前2個字節不同,所以轉換成STRING時候需要特殊處理,否則中文有亂碼

以下是我對幾種常用的編碼進行的分析
//獲取源代碼的編碼類別
                        //UNICODE
                        if(b[0]==0xFF && b[1]==0xFE)
                        {
                                return System.Text.Encoding.Unicode.GetString(b,0,b.Length);
                        }
                                //UNICODE BIG ENDIAN
                        else if(b[0]==0xFE && b[1]==0xFF)
                        {
                                return System.Text.Encoding.BigEndianUnicode.GetString(b,0,b.Length);
                        }
                                //UTF8
                        else if(b[0]==0xEF && b[1]==0xBB)
                        {
                                return System.Text.Encoding.UTF8.GetString(b,0,b.Length);
                        }
                                //DEFAULT ANSII
                        else
                        {
                                return System.Text.Encoding.Default.GetString(b,0,b.Length);
                        }

Timothy 2006-2-14 01:49
其中b是網頁源代碼的以二進制方式讀取的數組

王暴徒 2006-2-14 03:39
小強~呵呵,

Timothy 2006-2-14 05:38
這樣的也算小強阿,我一向都把你當我的偶像來的:)

王暴徒 2006-2-16 09:01
你是我偶像,把你那個程序詳細分析下給大家看看嘛。

Timothy 2006-2-16 10:14
我開始是想把它完善,然後和我的網站綁定,然後通過在程序開始或者結束彈出廣告
來賺錢,當我完成了一個模型的時候,就是能夠從百度對它的幾個分類(TOP500什麼的)進行批量下載的時候,
我同事說已經有人作了,我下載了看了下挺好的,不過還不人性化,有些需求沒有考慮到,
比如只能掛接BAIDU,沒有靈活配置的接口,使可以掛接其他網站,比如古典音樂
網站什麼的.但是很小,才300k,而我的.net作的東西太大了,有FREAMEWORK都快接近25M了,
別人說什麼也不會用,所以就暫停了,等我有時間多用VC重新弄個人性化的來玩玩.
現在要弄微軟路線的BI了,看看數據挖掘和報表服務,耽誤了工作以後就麻煩了.

百度也過分,知道有人老是通過它來下載歌曲,源代碼的結構經常改,有兩個辦法,一個是
你也經常去分析他的源代碼,發現變了,你趕快修改你的配置文件,其中配置文件放在
你的網站上,下載歌曲的程序運行時通過後臺線程去讀取它.這樣就是累.另外一個辦法就是
通過人工智能分析,比如讀取TOP500頁面後,上面有幾百首歌,讓程序自動去分析那些是
歌曲的顯示名稱,那些是連接的URL,哪些是序號什麼的,還有歌詞URL,這樣就對百度不變應萬變了,
呵呵,需要一定技術

今天玩檯球去了,明天貼點源代碼,主要是太多了,除非畫個UML圖.

Timothy 2006-2-17 01:32
我開始也寫了你和你一樣的單線程下載的類,不過後來通過增加一個委託,使他能夠實現同步和異步的調用,後來我在網上下載了一個兄弟的源代碼,他的是異步多線程調用,不過代碼有BUG,不能能多線程下載,但是架構很優美,我花了一個晚上時間把它修改了一下,爲了錯誤重試我個人方便,我增加了個別方法破壞了他的封裝性,有興趣看他的代碼的朋友可以在下面看
namespace Mp3Crazy
{
        using System;
        /// <summary>
        /// 包含 Exception 事件數據的類
        /// </summary>
        public class ExceptionEventArgs : System.EventArgs
        {
                private System.Exception _Exception;
                private ExceptionActions _ExceptionAction;

                private DownLoadState _DownloadState;

                public DownLoadState DownloadState
                {
                        get
                        {
                                return _DownloadState;
                        }
                }

                public Exception Exception
                {
                        get
                        {
                                return _Exception;
                        }
                }

                public ExceptionActions ExceptionAction
                {
                        get
                        {
                                return _ExceptionAction;
                        }
                        set
                        {
                                _ExceptionAction = value;
                        }
                }

                internal ExceptionEventArgs(System.Exception e, DownLoadState DownloadState)
                {
                        this._Exception = e;
                        this._DownloadState = DownloadState;
                }
        }

        /// <summary>
        /// 包含 DownLoad 事件數據的類
        /// </summary>
        public class DownLoadEventArgs : System.EventArgs
        {
                private DownLoadState _DownloadState;

                public DownLoadState DownloadState
                {
                        get
                        {
                                return _DownloadState;
                        }
                }

                public DownLoadEventArgs(DownLoadState DownloadState)
                {
                        this._DownloadState = DownloadState;
                }

        }

        public class ThreadProcessEventArgs : System.EventArgs
        {
                private string _id;
                public ThreadProcessEventArgs(string id)
                {
                        this._id=id;
                }

        }
}
 
Timothy 2006-2-17 01:33
namespace Mp3Crazy
{
        using System;

        /// <summary>
        /// 記錄下載的字節位置
        /// </summary>
        public class DownLoadState
        {
                private string _FileName;

                private string _AttachmentName;
                private int _Position;
                private string _RequestURL;
                private string _ResponseURL;
                private int _Length;

                private byte[] _Data;

                public string FileName
                {
                        get
                        {
                                return _FileName;
                        }
                }

                public int Position
                {
                        get
                        {
                                return _Position;
                        }
                }

                public int Length
                {
                        get
                        {
                                return _Length;
                        }
                }


                public string AttachmentName
                {
                        get
                        {
                                return _AttachmentName;
                        }
                }

                public string RequestURL
                {
                        get
                        {
                                return _RequestURL;
                        }
                }

                public string ResponseURL
                {
                        get
                        {
                                return _ResponseURL;
                        }
                }


                public byte[] Data
                {
                        get
                        {
                                return _Data;
                        }
                }

                internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, byte[] Data)
                {
                        this._FileName = FileName;
                        this._RequestURL = RequestURL;
                        this._ResponseURL = ResponseURL;
                        this._AttachmentName = AttachmentName;
                        this._Position = Position;
                        this._Data = Data;
                        this._Length = Length;
                }

                internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, ThreadCallbackHandler tch)
                {
                        this._RequestURL = RequestURL;
                        this._ResponseURL = ResponseURL;
                        this._FileName = FileName;
                        this._AttachmentName = AttachmentName;
                        this._Position = Position;
                        this._Length = Length;
                        this._ThreadCallback = tch;
                }

                internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length)
                {
                        this._RequestURL = RequestURL;
                        this._ResponseURL = ResponseURL;
                        this._FileName = FileName;
                        this._AttachmentName = AttachmentName;
                        this._Position = Position;
                        this._Length = Length;
                }

                private ThreadCallbackHandler _ThreadCallback;

                public HttpWebClient httpWebClient
                {
                        get
                        {
                                return this._hwc;
                        }
                        set
                        {
                                this._hwc = value;
                        }
                }

                private HttpWebClient _hwc;

                internal void StartDownloadFileChunk()
                {
                        if (this._ThreadCallback != null)
                        {
                                this._ThreadCallback(this._RequestURL, this._FileName, this._Position, this._Length);
                               
                                this._hwc.OnThreadProcess("");
                        }
                }

        }
}
Timothy 2006-2-17 01:33
/* .Net/C#: 實現支持斷點續傳多線程下載的工具類
* Reflector 了一下 System.Net.WebClient ,改寫或增加了若干:
* DownLoad、Upload 相關方法!
* 增加了 DataReceive、ExceptionOccurrs 事件
*/
namespace Mp3Crazy
{
        using System;
        using System.IO;
        using System.Net;
        using System.Text;
        using System.Security;
        using System.Threading;
        using System.Collections.Specialized;


        //委託代理線程的所執行的方法簽名一致
        public delegate void ThreadCallbackHandler(string S, string s, int I, int i);

        //異常處理動作
        public enum ExceptionActions
        {
                Throw,
                CancelAll,
                Ignore,
                Retry
        }

        /// <summary>
        /// 支持斷點續傳多線程下載的類
        /// </summary>
        public class HttpWebClient
        {

                public delegate void ExceptionEventHandler(HttpWebClient Sender, ExceptionEventArgs e);

                public event ExceptionEventHandler ExceptionOccurrs; //發生異常事件

                public delegate void ThreadProcessEventHandler(HttpWebClient Sender, ThreadProcessEventArgs e);

                public event ThreadProcessEventHandler ThreadProcessEnd; //發生多線程處理完畢事件


                private int _FileLength,_getLength; //下載文件的總大小
                public int TimeOut=20000;

                public int SongID=0;
                public bool UrlParsed;
                public string FileName;
                public bool Free=true;
                public int RetryTimes;
                public int TBlocks=1,curBlock;
                public int FileLength
                {
                        get
                        {
                                return _FileLength;
                        }
                }
                public int GetLength
                {
                        get
                        {
                                return _getLength;
                        }
                }

[[i] Last edited by Timothy on 2006-2-17 at 09:48 [/i]]

Timothy 2006-2-17 01:34
/// <summary>
                /// 分塊下載文件
                /// </summary>
                /// <param name="Address">URL 地址</param>
                /// <param name="FileName">保存到本地的路徑文件名</param>
                /// <param name="ChunksCount">塊數,線程數</param>
                public void DownloadFile(string Address, string FileName, int ChunksCount)
                {
                        int p = 0; // position
                        int s = 0; // chunk size
                        _getLength=0;
                        string a = null;
                        HttpWebRequest hwrq;
                        HttpWebResponse hwrp = null;
                        try
                        {
                                hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address));
                                hwrq.Timeout=TimeOut;
                                hwrp = (HttpWebResponse) hwrq.GetResponse();
                                //hwrq=null;
                                long L = hwrp.ContentLength;

                                hwrq.Credentials = this.m_credentials;

                                L = ((L == -1) || (L > 0x7fffffff)) ? ((long) 0x7fffffff) : L; //Int32.MaxValue 該常數的值爲 2,147,483,647; 即十六進制的 0x7FFFFFFF

                                int l = (int) L;

                                this._FileLength = l;

                                bool b = true;//(hwrp.Headers["Accept-Ranges"] != null && hwrp.Headers["Accept-Ranges"] == "bytes");
                                a = hwrp.Headers["Content-Disposition"]; //attachment
                                if (a != null)
                                {
                                        a = a.Substring(a.LastIndexOf("filename=") + 9);
                                }
                                else
                                {
                                        a = FileName;
                                }

                                int ss = s;
                                if (b)
                                {
                                        s = l / ChunksCount;
                                        if (s < 2 * 64 * 1024) //塊大小至少爲 128 K 字節
                                        {
                                                s = 2 * 64 * 1024;
                                        }
                                        ss = s;
                                        int i = 0;
                                        while (l >= s)
                                        {
                                                l -= s;
                                                if (l < s)
                                                {
                                                        s += l;
                                                }
                                                if (i++ > 0)
                                                {
                                                        DownLoadState x = new DownLoadState(Address, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s, new ThreadCallbackHandler(this.DownloadFileChunk));
                                                        //       單線程下載
                                                        //       x.StartDownloadFileChunk();

                                                        x.httpWebClient = this;
                                                        //多線程下載
                                                        Thread t = new Thread(new ThreadStart(x.StartDownloadFileChunk));
                                                        //this.OnThreadProcess(t);
                                                        t.Start();

                                                }
                                                p += s;
                                        }
                                        s = ss;
                                        this.ResponseAsBytes(Address, hwrp, s, FileName);
                                        this.OnThreadProcess("");
                                }
                        }
                        catch (Exception e)
                        {
                                if (this.ExceptionOccurrs != null)
                                {
                                        string path="";
                                        if(hwrp!=null)
                                                path=hwrp.ResponseUri.AbsolutePath;
                                        DownLoadState x = new DownLoadState(Address,path, FileName, a, p, s);
                                        ExceptionEventArgs eea = new ExceptionEventArgs(e, x);
                                        ExceptionOccurrs(this, eea);
                                }
                        }

                }

                internal void OnThreadProcess(string id)
                {
                        if (ThreadProcessEnd != null)
                        {
                                ThreadProcessEventArgs tpea = new ThreadProcessEventArgs(id);
                                ThreadProcessEnd(this, tpea);
                        }
                }

                /// <summary>
                /// 下載一個文件塊,利用該方法可自行實現多線程斷點續傳
                /// </summary>
                /// <param name="Address">URL 地址</param>
                /// <param name="FileName">保存到本地的路徑文件名</param>
                /// <param name="Length">塊大小</param>
                public void DownloadFileChunk(string Address, string FileName, int FromPosition, int Length)
                {
                        HttpWebResponse hwrp = null;
                        string a = null;
                        try
                        {
                                //this._FileName = FileName;
                                HttpWebRequest hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address));
                                //hwrq.Credentials = this.m_credentials;
                                hwrq.AddRange(FromPosition);
                                hwrp = (HttpWebResponse) hwrq.GetResponse();
                                hwrq=null;

                                a = hwrp.Headers["Content-Disposition"]; //attachment
                                if (a != null)
                                {
                                        a = a.Substring(a.LastIndexOf("filename=") + 9);
                                }
                                else
                                {
                                        a = FileName;
                                }

                                this.ResponseAsBytes(Address, hwrp, Length, FileName);
                        }
                        catch (Exception e)
                        {
                                if (this.ExceptionOccurrs != null)
                                {
                                        DownLoadState x = new DownLoadState(Address, hwrp.ResponseUri.AbsolutePath, FileName, a, FromPosition, Length);
                                        ExceptionEventArgs eea = new ExceptionEventArgs(e, x);
                                        ExceptionOccurrs(this, eea);
                                }
                        }
                }

                internal void ResponseAsBytes(string RequestURL, WebResponse Response, long Length, string FileName)
                {  
                        string a = null; //AttachmentName
                        int P = 0; //整個文件的位置指針
                        int num2 = 0;
                        try
                        {
                                a = Response.Headers["Content-Disposition"]; //attachment
                                if (a != null)
                                {
                                        a = a.Substring(a.LastIndexOf("filename=") + 9);
                                }

                                int p = 0; //本塊的位置指針
                                int num1=(int)Length;

                                byte[] buffer1 = new byte[30000];

                                string s = Response.Headers["Content-Range"];
                                if (s != null)
                                {
                                        s = s.Replace("bytes ", "");
                                        s = s.Substring(0, s.IndexOf("-"));
                                        P = Convert.ToInt32(s);
                                }

                                Stream S = Response.GetResponseStream();
                                System.IO.FileStream sw = new System.IO.FileStream(FileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
                                //Console.WriteLine("P:{0}",P);
                                do
                                {
                                        num2 = S.Read(buffer1, 0,30000);

                                        if (num2 > 0)
                                        {
                                                sw.Position = P;
                                                sw.Write(buffer1,0,num2);
                                                p += num2; //本塊的位置指針
                                                P += num2; //整個文件的位置指針
                                                _getLength+=num2;
                                                //Console.WriteLine("{0}",(_getLength*100/_FileLength));
                                        }
                                        else
                                        {
                                                break;
                                        }

                                }
                                while (num1>p);

                                sw.Close();
                                S.Close();

                                buffer1=null;
                                sw=null;
                                S = null;
                                Response = null;
                        }
                        catch (Exception e)
                        {
                                if (this.ExceptionOccurrs != null)
                                {
                                        DownLoadState x = new DownLoadState(RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2);
                                        ExceptionEventArgs eea = new ExceptionEventArgs(e, x);
                                        ExceptionOccurrs(this, eea);
                                }
                        }
                }

                private byte[] ResponseAsBytes(WebResponse response)
                {
                        int num2;
                        long num1 = response.ContentLength;
                        bool flag1 = false;
                        if (num1 == -1)
                        {
                                flag1 = true;
                                num1 = 0x10000;
                        }
                        byte[] buffer1 = new byte[(int) num1];
                        Stream stream1 = response.GetResponseStream();
                        int num3 = 0;
                        do
                        {
                                num2 = stream1.Read(buffer1, num3, ((int) num1) - num3);
                                num3 += num2;
                                if (flag1 && (num3 == num1))
                                {
                                        num1 += 0x10000;
                                        byte[] buffer2 = new byte[(int) num1];
                                        Buffer.BlockCopy(buffer1, 0, buffer2, 0, num3);
                                        buffer1 = buffer2;
                                }
                        }
                        while (num2 != 0);
                        stream1.Close();
                        if (flag1)
                        {
                                byte[] buffer3 = new byte[num3];
                                Buffer.BlockCopy(buffer1, 0, buffer3, 0, num3);
                                buffer1 = buffer3;
                        }
                        return buffer1;
                }

                private NameValueCollection m_requestParameters;
                private Uri m_baseAddress;
                private ICredentials m_credentials = CredentialCache.DefaultCredentials;

                public ICredentials Credentials
                {
                        get
                        {
                                return this.m_credentials;
                        }
                        set
                        {
                                this.m_credentials = value;
                        }
                }

                public NameValueCollection QueryString
                {
                        get
                        {
                                if (this.m_requestParameters == null)
                                {
                                        this.m_requestParameters = new NameValueCollection();
                                }
                                return this.m_requestParameters;
                        }
                        set
                        {
                                this.m_requestParameters = value;
                        }
                }

                public string BaseAddress
                {
                        get
                        {
                                if (this.m_baseAddress != null)
                                {
                                        return this.m_baseAddress.ToString();
                                }
                                return string.Empty;
                        }
                        set
                        {
                                if ((value == null) || (value.Length == 0))
                                {
                                        this.m_baseAddress = null;
                                }
                                else
                                {
                                        try
                                        {
                                                this.m_baseAddress = new Uri(value);
                                        }
                                        catch (Exception exception1)
                                        {
                                                throw new ArgumentException("value", exception1);
                                        }
                                }
                        }
                }

                private Uri GetUri(string path)
                {
                        Uri uri1;
                        try
                        {
                                if (this.m_baseAddress != null)
                                {
                                        uri1 = new Uri(this.m_baseAddress, path);
                                }
                                else
                                {
                                        uri1 = new Uri(path);
                                }
                                if (this.m_requestParameters == null)
                                {
                                        return uri1;
                                }
                                StringBuilder builder1 = new StringBuilder();
                                string text1 = string.Empty;
                                for (int num1 = 0; num1 < this.m_requestParameters.Count; num1++)
                                {
                                        builder1.Append(text1 + this.m_requestParameters.AllKeys[num1] + "=" + this.m_requestParameters[num1]);
                                        text1 = "&";
                                }
                                UriBuilder builder2 = new UriBuilder(uri1);
                                builder2.Query = builder1.ToString();
                                uri1 = builder2.Uri;
                        }
                        catch (UriFormatException)
                        {
                                uri1 = new Uri(Path.GetFullPath(path));
                        }
                        return uri1;
                }

        }

}
Timothy 2006-2-17 01:45
這個是如何使用的一個simple demo

namespace MultiThread
{
        using System;
        using System.IO;
        using System.Net;
        using System.Text;
        using System.Security;
        using System.Threading;
        using System.Collections;
        using System.Collections.Specialized;
        using Mp3Crazy;
        /// <summary>
        /// 測試類
        /// </summary>
        class AppTest
        {
                int _k = 0;
                int _K = 0;

                static void Main()
                {
                        //FileStream fs=File.
                        //fs.
                        //System.Text.Encoding.UTF8
//                        int i;
//                        DBAccess.InitConn();
//                        for(i=0;i<26;i++)
//                        {
//                                DBAccess.ExcuteNoquery("insert into Node(Name,FID,Url,IsSinger) values('"+(char)(i+65)+"',10,'http://list.mp3.baidu.com/song/"+(char)(i+65)+".htm',0)");
//                        }
//                        DBAccess.DestroyConn();
//                        return;

                        go();
                        GC.Collect();

                        string str=System.Console.ReadLine();
                        //for(int j=0;;);
                        //  string uploadfile = "e://test_local.rar";
                        //  string str = x.UploadFileEx("http://localhost/phpmyadmin/uploadaction.php", "POST", uploadfile, "file1");
                        //  System.Console.WriteLine(str);
                        //  System.Console.ReadLine();
                }

                private static void go()
                {
                        int i=0;
                        for(i=0;i<3;i++)
                        {
                                AppTest a = new AppTest();
                                HttpWebClient x = new HttpWebClient();
                                x.TBlocks=2;
                                x.curBlock=0;
                                a._K =2;
                                x.TimeOut=10000;

                                //訂閱 DataReceive 事件
                                //x.DataReceive += new Microshaoft.Utils.HttpWebClient.DataReceiveEventHandler(a.x_DataReceive);
                                //訂閱 ExceptionOccurrs 事件
                                x.ExceptionOccurrs += new HttpWebClient.ExceptionEventHandler(a.x_ExceptionOccurrs);

                                x.ThreadProcessEnd += new HttpWebClient.ThreadProcessEventHandler(a.x_ThreadProcessEnd);
                                string F = "http://localhost/gsx.MP3";
                                a._F = F;

                                string f = F.Substring(F.LastIndexOf("/") + 1)+i.ToString();
                                a._f =f;

                                //(new System.Threading.Thread(new System.Threading.ThreadStart(new ThreadProcessState(F, @"E:/temp/" + f, 10, x).StartThreadProcess))).Start();

                                x.DownloadFile(F, @"E:/" + f, a._K);
                        }
                }
                string _F;
                string _f;

                private void x_ExceptionOccurrs(HttpWebClient Sender, ExceptionEventArgs e)
                {
                        System.Console.WriteLine(e.Exception.Message);
                        //發生異常重新下載相當於斷點續傳,你可以自己自行選擇處理方式
                        HttpWebClient x = new HttpWebClient();
                        x.DownloadFileChunk(this._F, this._f, e.DownloadState.Position, e.DownloadState.Length);
                        e.ExceptionAction = ExceptionActions.Ignore;
                }

                private void x_ThreadProcessEnd(HttpWebClient Sender, ThreadProcessEventArgs e)
                {
                        //if (e.thread.ThreadState == System.Threading.ThreadState.Stopped)
                        //if (this._k ++ == this._K - 1)
                        if(Sender.curBlock++==Sender.TBlocks-1)
                                System.Console.WriteLine("end/n");
                        GC.Collect();
                }
        }

        class Test
        {
                public static void Main2()
                {
                        // Create a new 'HttpWebRequest' Object to the mentioned URL.
                        HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://localhost/default.aspx");
                        myHttpWebRequest.AddRange(50,100);
                       
                        // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
                        HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
                        bool b=(myHttpWebRequest.Headers["Range"] != null && myHttpWebRequest.Headers["Range"].ToLower().StartsWith( "bytes"));
                        Console.WriteLine("/nThe HttpHeaders are /n/n/tName/t/tValue/n{0}",myHttpWebRequest.Headers);
                        IEnumerator ie=myHttpWebRequest.Headers.GetEnumerator();
                        while(ie.MoveNext())
                                Console.WriteLine("key:{0}",ie.Current.ToString());
                        // Print the HTML contents of the page to the console.
                        long i=myHttpWebResponse.ContentLength;
                        Stream streamResponse=myHttpWebResponse.GetResponseStream();
                        StreamReader streamRead = new StreamReader( streamResponse );
                        Char[] readBuff = new Char[256];
                        int count = streamRead.Read( readBuff, 0, 256 );
                        Console.WriteLine("/nThe HTML contents of page the are  : /n/n ");   
                        while (count > 0)
                        {
                                String outputData = new String(readBuff, 0, count);
                                Console.Write(outputData);
                                count = streamRead.Read(readBuff, 0, 256);
                        }
                        // Close the Stream object.
                        streamResponse.Close();
                        streamRead.Close();
                        // Release the HttpWebResponse Resource.
                        myHttpWebResponse.Close();

                        Console.ReadLine();

                }
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章