.NETC #: Implement the HTTP web client tool class for support breakpoints to renew multi-thread download (C # DIY HTTPWEBCLIENT)

xiaoxiao2021-03-06  14

/ * .NET / C #: Implement the HTTP web client tool class (C # diy httpwebclient) * Reflector, the Reflector, the reserver, or add a number of: * Download, UPLOAD Method! * Download related changes! * Added DataReceive, ExceptionOccurrs event! * Understand the HTTP protocol of the server-side interaction with the client to see: * Make the custom connection of the file download to support the flash link download! JSP / servlet implementation! * Http://blog.9cbs.net/playyueer/archive/2004/08/02/58430.aspx * Make a custom connection to file download support FlashGet breakpoint renewal multi-thread link download! C # /ASP.NET implementation! * Http://blog.9cbs.net/playyuer/archive/2004/08/02/58281.aspx * /

namespace Microshaoft.Utils {using System; using System.IO; using System.Net; using System.Text; using System.Security; using System.Threading; using System.Collections.Specialized; ///

/// recorded Download byte position /// public class downloadstate {private string _filename

Private string _ttachmentname; 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._ens = 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;

// INTERNAL VOID StartDownloadFilechunk () {if (this._threadcallback! = Null) {this._threadcallback (this._requesturl, this._filename, this._position, this._length);}}

}

/ / Enter the method of executing the proxy thread signing uniform public delegate Void ThreadCallbackHandler (String S, String S, INT I, INT i);

// Abnormal processing action public enum exceptionActions {throw, cacall, ignore, retry}

///

/// event data comprising Exception class /// 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 EXCETIONACTIONES EXCETIONACTION {Get {Return _ExceptionAction;} set {_exceptionAction = value;}}

INTERNAL EXCEPTIONEVENTARGS (System.Exception E, DownloadState DownloadState) {this._exception = E; this._downloadstate = DownloadState;}}

///

/// includes a class /// public class downloadeventArgs: system.eventargs {private design;

Public DownloadState DownloadState {Get {Return_downloadState;}}

Public DownloadState {THIS._DOWNLOADSTATATE = DownloadState;

}

///

/// Support breakpoint to renew multi-thread download class /// public class httpwebclient {private static object _synclockObject = new object ();

Public Delegate Void DataReceiveEventHandler (HttpWebClient Sender, DownloadEventAndargs E);

Public Event DataReceiveEventHandler DataReceive; // Receive Byte Data Event

Public Delegate Void ExceptionEventHandler (HttpWebClient Sender, ExceptionEventArgs E);

Public Event ExceptionEventHandler ExceptionOccurrs; // A abnormal event occurs

Private int _fileLength; // Download the total size of the file

Public int filelength {get {return _fileLength;}}

///

/// 分 块 下载 下载 /// /// URL address /// Save to Local path file name /// number, number of threads public void Downloadfile (String address, string filename, int chunkscount) {int P = 0; // position int s = 0; // chunk size string a = null; HttpWebRequest hwrq; HttpWebResponse hwrp = null; try {hwrq = (HttpWebRequest) WebRequest.Create (this.GetUri (Address)); hwrp = (HttpWebResponse) hwrq.GetResponse (); Long l = hwrp.contentLength; hwrq.credentials = this.m_credentials;

L = ((l == -1) || (L> 0x7fffffff))? ((Long) 0x7fffffff): L; //int32.maxvalue This constant is 2,147,483,647; ie hexadecimal 0x7fffffffFFFFFFFFFFFFFFFFFF

INT L = (int) L;

THIS._FILENGTH = L;

// In the local predetermined space (actually do not have a predetermined space in multi-thread) // filestream sw = new filestream (filename, filemode.openorcreate, fileaccess.readwrite, fileshare.readwrite); // sw.write (New Byte [L ], 0, l); // sw.close (); // SW = NULL;

Bool B = (hwrp.headers]! = 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) // block size is at least 128 k byte {s = 2 * 64 * 1024;} ss = s; INT i = 0; While (L> S) {L - = S; if (l 0) {DownloadState X = New DownloadState (address, hwrp.responseuri.absolutePath , FileName, a, p, s, new ThreadCallbackHandler (this.DownloadFileChunk)); // threaded download // x.StartDownloadFileChunk (); // multithreaded download // thread t = new thread (new ThreadStart (x.StartDownloadFileChunk ))))). START (); //t.Start ();} p = s;} s = ss; byte [] buffer = this.Responseasbytes (Address, HWRP, S, FileName);

// lock (_SyncLockObject) // {// this._Bytes = buffer.Length; //}}} catch (Exception e) {ExceptionActions ea = ExceptionActions.Throw; if (! This.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (Address, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s); ExceptionEventArgs eea = new ExceptionEventArgs (e, x); ExceptionOccurrs (this, eea); ea = eea.ExceptionAction;}

IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("net_webclient", e);} throw;}}

}

///

/// Download a file block, using this method to implement multi-line comparison points /// /// URL address /// Saved to local path file name /// block size 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 = HWRQ.AddRedentials; hwrq.addrange (hwrp = (httpwebresponse) hwrq.getResponse (); a = hwrp.headers ["content-disposition"]; // attachment if (a! = null) {a = a. Substring ("FileName =") 9);} else {a = filename;} byte [] buffer = this.responseasbytes (address, hwrp, length, filename); // Lock (_SyncLockObject) // { // this._bytes = buffer.length; ///}} catch (exception e) {exceptionactions ea = exceptionactions.throw; 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) EA = eea.exception;

IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("Net_WebClient", E);} through;}}}

INTERNAL BYTE [] Responseasbytes (String Requesturl, WebResponse Response, long length, string filename) {string a = null; // attachmentname int P = 0; // The position pointer of the entire file INT NUM2 = 0; Try {a = response. Headers ["Content-Disposition"]; // attachment if (a! = Null) {a = a.substring (a.lastIndexof ("filename =") 9);} long Num1 = length; //Response.contentLENGTH Bool flag1 = false; if (Num1 == -1) {flag1 = true; Num1 = 0x10000; // 64k} byte [] buffer1 = new byte [(int) Num1];

INT P = 0; // This block of position pointer

String s = response.Headers ["content-range"]; if (s! = null) {s = s.replace ("bytes", "); s = s.substring (0, s.indexof) ")); P = convert.toint32 (s);} int Num3 = 0;

Stream S = response.getResponseSstream (); do {Num2 = S. 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;}

// Lock (_SyncLockObject) // {// this._bytes = Num2; //} f (Num2> 0) {if (this.DataReceive! = Null) {byte [] buffer = new byte [Num2]; buffer .BlockCopy (buffer1, p, buffer, 0, buffer.Length); DownLoadState dls = new DownLoadState (RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2, buffer); DownLoadEventArgs dlea = new DownLoadEventArgs (dls); // Trigger event this.ondatareceive (DLEA); //system.threading.thread.sleep(100);} P = Num2; // This block position pointer P = Num2; // The position pointer of the entire file} Else {Break;

} While (Num2! = 0);

S.close (); s = null; if (flag1) {byte [] buffer3 = new byte [Num3]; buffer1, 0, buffer3, 0, num 3); buffer1 = buffer3;} return buffer1;} catch (Exception e) {ExceptionActions ea = ExceptionActions.Throw; if (! this.ExceptionOccurrs = null) {DownLoadState x = new DownLoadState (RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2); ExceptionEventArgs eea = new ExceptionEventArgs (E, X); Exceptionocurrs (this, EEA); EA = EEA.Exception;

IF (EA == ExceptionActions.throw) {if (! (e is webexception) &&! ("Net_WebClient", E);} throw;}}}}}}} Return NULL

Private void OnDataReceive (DownloadEventArgs E) {// Trigger data arrival event DataReceive (this, e);}

Public Byte [] UPLOADFILE (STRING Address, String FileName) {Return this.uploadFile (Address, "Post", FileName, "File");}

public string UploadFileEx (string address, string method, string fileName, string fieldName) {return Encoding.ASCII.GetString (UploadFile (address, method, fileName, fieldName));} public byte [] UploadFile (string address, string method, string FileName, String FieldName) {byte [] buffer4; filestream stream1 = null; try {filename = path.getFullPath (filename); string text1 = "----------------- - " DateTime.now.ticks.tostring (" x ");

String text2 = "Application / OcTet-stream";

stream1 = new FileStream (fileName, FileMode.Open, FileAccess.Read); WebRequest request1 = WebRequest.Create (this.GetUri (address)); request1.Credentials = this.m_credentials; request1.ContentType = "multipart / form-data; Boundary = " Text1;

Request1.method = method; string [] textArray1 = new string [7] {"-", text1, "/ r / ncontent-disposition: form-data; name = /" fieldname "/"; filename = / "" ", Path.getfilename (filename)," / "/" / r / nContent-type: ", text2," / r / n / r / n "}; string text3 = string.concat (TextArray1); byte [] Buffer1 = encoding.utf8.getbytes (text3); byte [] buffer2 = encoding.ascii.getbytes ("/ r / n" text1 "/ r / n"); long Num1 = 0x7fffffffffffffffff; Try {Num1 = Stream1.Length; Request1.contentLength = (Num1 Buffer1.Length) Buffer2.Length;} catch {} byte [] buffer3 = new byte [Math.min (0x2000, (int) Num1)]; use)]; use)]; using (stream stream2 = Request1.getRequestStream ()) {Int Num2; stream2.write (buffer1, 0, buffer1.Length); do {Num2 = stream1.read (buffer3, 0, buffer3.length); if (Num2! = 0) {stream2. Write (Buffer3, 0, Num2);}} while (Num2! = 0); stream2.write (buffer2, 0, buffer2.Length);} stream1.close (); stream1 = Null; WebResponse response1 = request1.GetResponse (); buffer4 = this.ResponseAsBytes (response1);} catch (Exception exception1) {if (stream1 = null!) {Stream1.Close (); stream1 = null;} if (! (exception1 is WebException) && (exception1 is SecurityException)) {// throw new WebException (SR.GetString ( "net_webclient"), exception1); throw new WebException ( "net_webclient", exception1);}! throw;} return buffer4; }

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.getResponseSstream (); 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]; buffer1, 0, buffer3, 0, num3); buffer1 = buffer3;} Return buffer1;} private namevaluecollection m_requestparameters; private uri m_baseaddress; private icredentials m_credentials = credentialcache.defaultcredentials;

Public ictedentials credentials {get {returnim_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) {returnim_baseaddress.tostring ();} return string.empty;} set {i ((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

}

}

///

/// Test class /// class appteest {static void main () {apptest a = new apptest (); microshaoft.utils.httpwebclient x = new microshaoft.utils.httpwebclient () ;

// Subscribe DataReceive event x.DataReceive = new Microshaoft.Utils.HttpWebClient.DataReceiveEventHandler (a.x_DataReceive); // subscribe ExceptionOccurrs event x.ExceptionOccurrs = new Microshaoft.Utils.HttpWebClient.ExceptionEventHandler (a.x_ExceptionOccurrs); string F = "http://localhost/download/phpmyadmin-2.6.1-pl2.zip"; A._F = f; f = "http://localhost/download/jdk-1_5_0_01-windows-i586-p.aa. EXE "; // f =" http://localhost/download/resharper1.5.exe ";

// f = "http://localhost/mywebapplications/webapplication7/webform1.aspx"; // f = "http: // localhost: 1080 / test / demary.jsp";

// f = "http://localhost/download/webcast20050125_ppt.zip"; // f = "http://www.morequick.com/greenbrowsergb.zip"; // f = "http: // localhost / download / Test_local.rar "; string f = f.substring (f.lastIndexof (" / ") 1);

// (New System.Threading.Thread (New System.Threading.ThreadStart (New ThreadProcessState (f, @ "E: / TEMP /" F, 10, x) .startthreadProcess))))))). Start ();

x.downloadfile (f, @ "e: / temp / temp /" f, 10); // x.downloadfilechunk (f, @ "E: / TEMP /" F, 15, 34556);

System.console.readline (); // upload test // 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 ();}

String BS = ""; // Used to record the last bit number BOOL B = false; private int i = 0; private static object _synclockObject = new object (); string _f; string _f;

private void x_DataReceive (Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.DownLoadEventArgs e) {if (! this.b) {lock (_SyncLockObject) {if (! this.b) {System.Console.Write (System.DateTime. Now.toTString () "has received data:"); //system.console.write (system.datetime.now.tostring () "has received data:"); this.b = true;}} F = E.DownloadState.FileName; if (e.downloadstate.attachmentName! = null) f = system.io.path.getdirectoryName (f) @ "/" E.DownloadState.attachmentName; this._f = f;

Using (System.IO.FileStream SW = New System.io.FileStream (f, system.io.filemode.openorcreate, system.io.filecess.readwrite, system.io.fileshare.readwrite) {sw.position = e. DownloadState.position; sw.write (E.DownloadState.Data, 0, E.DownloadState.Data.Length); sw.close ();} string s = system.datetime.now.tostring (); lock.tostring (); lock.tockObject THIS.I = E.DownloadState.Data.Length; System.Console.write (BS "/ B / B / B / B / B / B / B / B / B / B / B" i "/" Sender.fileLength "byte data" s); //system.console.write (BS i "byte data" s); this.bs = new string ('/ b', DIGITS (i) 3 Digits (Sender.FileLength) S.Length);}}

INT DIGITS (INT N) // Number of places {n = system.math.abs (n = n / 10; int i = 1; while (n> 0) {n = N / 10; i } Return i;}

转载请注明原文地址:https://www.9cbs.com/read-49899.html

New Post(0)