Upload files to the server through the HTTP protocol in WinForm

xiaoxiao2021-03-06  45

I believe that using ASP.NET writes a web page for uploading files. Everyone will write, but have anyone thinks to upload files through the HTTP protocol through the WinForm?

Some people say that the file is to be on the server, isn't it very simple to use the FTP protocol? The efficiency is high, why should I use the HTTP agreement so trouble? There are several reasons this:

(

1

) The deployment of the FTP server is relatively trouble, but also set permissions, permission settings are not correct, will also provoke a series of security issues.

(

2

If both parties have firewalls, they do not want to develop some port related to FTP, http will be used to use, just like Web Services can wear firewalls.

(

3

) Other ..., still think ...

But use HTTP and some of his problems, such as can't be broken, it is difficult to upload big files, slow speed, so the file size uploaded by HTTP protocol should not be too big.

Said so much, original home, in general, there are several optional methods to upload files in WinForm:

(

1

The web services mentioned earlier is a good way to include a WebMethod, including

Byte

[] Parameters of the type, then call the web services, the file content is transmitted to the server as Base64, and then re-save.

[WebMethod]

public

Void

UPLOADFILE

Byte

Content,

String

Filename)

...

{

Street SW = new streamwriter (...);

SW.CLOSE ();

}

Of course, this method of efficiency by Base64 encoding is relatively low, then WSE can be employed, and attachments can be used, and the efficiency will be higher in 2 envelopes.

(

2

In addition to the WebService, another simple method is to simulate the POST action of HTTP through WebClient or HttpWebRequest. At this time, you first need to write an ASP.NET web form to respond to upload, the code is as follows:

Webform1 </ Title></p> <p><meta name = "generator" content = "Microsoft Visual Studio .NET 7.1"></p> <p><meta name = "code_language" content = "c #"></p> <p><meta name = "vs_defaultclientscript" content = "javascript"></p> <p><meta name = "vs_targetschema" content = "http://schemas.microsoft.com/intellisense/ie5"></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" method = "post" runat = "server"> </ form></p> <p></ body></p> <p></ html></p> <p>Using</p> <p>System;</p> <p>Using</p> <p>System.collections;</p> <p>Using</p> <p>System.componentmodel;</p> <p>Using</p> <p>System.data;</p> <p>Using</p> <p>System.drawing;</p> <p>Using</p> <p>System.Web;</p> <p>Using</p> <p>System.Web.SessionState;</p> <p>Using</p> <p>System.Web.ui;</p> <p>Using</p> <p>System.Web.ui.WebControls;</p> <p>Using</p> <p>System.Web.ui.htmlControls;</p> <p>Namespace</p> <p>UploadFileWeb</p> <p>...</p> <p>{</p> <p>/ ** //// <summary></p> <p>/// WebForm1 summary description.</p> <p>/// </ summary></p> <p>Public class Webform1: System.Web.ui.page</p> <p>... {</p> <p>Private Void Page_Load (Object Sender, System.EventArgs E)</p> <p>... {</p> <p>/ / Place the user code here to initialize the page</p> <p>FOREACH (String f in request.files.allkeys)</p> <p>... {httppostedfile file = request.files [f]; file.saves (@ "d: / temp /" file.filename);</p> <p>IF (Request.Params ["TestKey"]! = NULL)</p> <p>... {response.write (Request.Params ["TestKey"]);</p> <p>}</p> <p>Web Form Designer Generated Code #Region Web Form Designer Generated Code</p> <p>Override protected void oninit (Eventargs E)</p> <p>... {// // Codegen: This call is required for the ASP.NET Web Form Designer. // InitializeComponent (); base.oninit (e);</p> <p>/ ** //// <summary> /// Designer supports the required method - Do not use the code editor to modify the // / this method. /// </ summary></p> <p>Private vidinitiRizeComponent ()</p> <p>... {this.Load = new system.eventhandler (this.page_load);</p> <p>#ndregion</p> <p>}</p> <p>}</p> <p>In fact, this page is the same as our usual written ASP.NET upload file code. In the REQUEST object in the web page, this object contains this object, which contains information on all files uploaded by the Post method. It is called the Request.Files [i] .saves method.</p> <p>But how can you only simulate Web Form Post data in WinForm? Two very useful classes are provided in the System.Net namespace, one is WebClient, and the other is the HTTPWebRequest class. If we don't need to upload files through the proxy server, it is very simple, just simply call the WebClient.uploadFile method to upload files:</p> <p>Private</p> <p>Void</p> <p>Button1_click</p> <p>Object</p> <p>Sender, System.EventArgs E)</p> <p>...</p> <p>{</p> <p>WebClient MyWebClient = new WebClient (); MyWebClient.uploadFile ("http://localhost/uploadfileweb/webform1.aspx", "post", @ "d: /temp/java/javastart/javastart2.exe");</p> <p>}</p> <p>Is it very simple? It is really so simple.</p> <p>But what should I do if I want to upload through the proxy server? Then you need to use HttpWebRequest, but this class does not have an UPLOAD method, but fortunately we compile the WebClient.uploadFile method through the Reflector, we found that it is also implemented inside the WebRequest, the code is as follows:</p> <p>public</p> <p>Byte</p> <p>UPLOADFILE</p> <p>String</p> <p>Address,</p> <p>String</p> <p>Method,</p> <p>String</p> <p>Filename)</p> <p>...</p> <p>{</p> <p>String text1;</p> <p>String text2;</p> <p>WebRequest Request1;</p> <p>String text3;</p> <p>BYTE [] Buffer1;</p> <p>BYTE [] buffer2;</p> <p>Long Num1;</p> <p>BYTE [] Buffer3;</p> <p>Int Num2;</p> <p>WebResponse Response1;</p> <p>BYTE [] Buffer4;</p> <p>Datetime Time1;</p> <p>Long Num3;</p> <p>String [] TextArray1;</p> <p>FileStream Stream1 = NULL;</p> <p>Try</p> <p>... {</p> <p>FileName = path.getFullPath (filename);</p> <p>Time1 = DATETIME.NOW;</p> <p>Num3 = TIME1.TICKS;</p> <p>Text1 = "-------------------" Num3.toString ("x");</p> <p>IF (this.m_headers == NULL)</p> <p>... {</p> <p>THIS.M_HEADERS = New WebHeaderCollection ();</p> <p>}</p> <p>TEXT2 = this.m_headers ["content-type"];</p> <p>IF (Text2! = NULL)</p> <p>... {</p> <p>IF (Text2.Tolower (CultureInfo.invariantCulture) .startswith ("Multipart /"))</p> <p>... {throw new WebException (sr.getstring ("net_webclient_multipart"));</p> <p>}</p> <p>Else</p> <p>... {</p> <p>Text2 = "Application / OCTET-stream";</p> <p>}</p> <p>THIS.M_HEADERS ["Content-Type"] = "Multipart / Form-Data; Boundary =" TEXT1;</p> <p>THIS.M_RESPONSEHEADERS = NULL;</p> <p>Stream1 = New FileStream (FileName, Filemode.Open, FileAccess.Read);</p> <p>Request1 = WebRequest.create (this.Geturi (address));</p> <p>REQUEST1.CREDENTIALS = this.credentials;</p> <p>This.copyheadersto (Request1);</p> <p>Request1.method = method;</p> <p>TextArray1 = new string [7]; TextArray1 [0] = "-"</p> <p>TextArray1 [1] = text1;</p> <p>TEXTARRAY1 [2] = "/ r / nContent-disposition: form-data; name = /" file / "; filename = /" "</p> <p>TextArray1 [3] = path.getFileName (filename);</p> <p>TextArray1 [4] = "/" / r / nContent-type: "</p> <p>TextArray1 [5] = text2;</p> <p>TextArray1 [6] = "/ r / n / r / n";</p> <p>Text3 = String.concat (TextArray1);</p> <p>Buffer1 = encoding.utf8.getbytes (Text3);</p> <p>Buffer2 = encoding.ascii.getbytes ("/ R / N--" Text1 "/ R / N");</p> <p>Num1 = 9223372036854775807;</p> <p>Try</p> <p>... {</p> <p>Num1 = stream1.length;</p> <p>REQUEST1.CONTENTLENGTH = ((Num1 ((long) buffer1.length) ((long) buffer2.length);</p> <p>}</p> <p>Catch</p> <p>... {</p> <p>}</p> <p>Buffer3 = new byte [math.min ((int) 8192), ((int) Num1))];</p> <p>USING (stream stream2 = request1.getRequestStream ())</p> <p>... {</p> <p>Street2.write (buffer1, 0, buffer1.length);</p> <p>DO</p> <p>... {Num2 = stream1.read (buffer3, 0, buffer3.Length); if (Num2! = 0) ... {stream2.write (buffer3, 0, num2);}}</p> <p>While ((NUM2! = 0));</p> <p>Street2.write (buffer2, 0, buffer2.length);</p> <p>}</p> <p>Street1.close ();</p> <p>stream1 = null;</p> <p>Response1 = Request1.getResponse ();</p> <p>THIS.M_RESPONSEHEADERS = response1.Headers;</p> <p>Return this.Responseasbytes (response1);</p> <p>}</p> <p>Catch (Exception Exception1)</p> <p>... {</p> <p>IF (stream1! = null)</p> <p>... {</p> <p>Street1.close ();</p> <p>stream1 = null;</p> <p>}</p> <p>IF ((Exception1 IS WebException) || (Exception1 Is SecurityException))</p> <p>... {</p> <p>Throw;</p> <p>}</p> <p>Throw new WebException (Sr.getstring ("Net_WebClient"), Exception1);</p> <p>}</p> <p>Return buffer4;</p> <p>}</p> <p>In this code, the most critical is how to simulate the POST request. By analyzing the code and monitoring HTTP, we can find that the Simulated POST format is as follows:</p> <p>-----------------------</p> <p>8c64f47716481f0</p> <p>//</p> <p>Timestamp</p> <p>Content</p> <p>-</p> <p>Disposition: Form-</p> <p>Data; Name</p> <p>=</p> <p>"</p> <p>File</p> <p>"</p> <p>FILENAME</p> <p>=</p> <p>"</p> <p>a.txt</p> <p>"</p> <p>//</p> <p>file name</p> <p>Content</p> <p>-</p> <p>TYPE: Application</p> <p>/</p> <p>Octet</p> <p>-</p> <p>Stream</p> <p>//</p> <p>File content</p> <p>-----------------------</p> <p>8c64f47716481f0</p> <p>At this time, we only need to code to simulate such a set of data (we can also learn from the MS code), the following is the code (declaration, I borrowed the code of others)</p> <p>public</p> <p>Class</p> <p>WWHTTP</p> <p>...</p> <p>{</p> <p>/ ** //// <summary></p> <p>/// Fires Progress Events When Using geturLevents () TO Retrieve A URL.</p> <p>/// </ summary></p> <p>Public Event OnreceiveDataHandler OnreceiveData;</p> <p>/ ** //// <summary></p> <p>/// DETERMINESHOW DATA IS Posted When CPostBuffer IS Set.</p> <p>/// 1 - Urlencoded</p> <p>/// 2 - Multi-Part Form Vars</p> <p>/// 4 - xml (Raw Buffer Content Type: Text / XML)</p> <p>/// </ summary></p> <p>Public int Postmode</p> <p>... {</p> <p>Get ... {return this.npostmode;}</p> <p>Set ... {this.npostmode = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// user name buy for automation.</p> <p>/// to use the currently logged in User When Accessing An ntlm resource you can use "autological".</p> <p>/// </ summary></p> <p>Public String Username</p> <p>... {</p> <p>Get ... {return this.cusername;}</p> <p>Set ... {cusername = value;}</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Password for automation.</p> <p>/// </ summary></p> <p>Public String Password</p> <p>... {</p> <p>Get ... {return this.cpassword;}</p> <p>Set ... {this.cpassword = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// address of the proxy server to be used.</p> <p>/// Use Optional defaultproxy value to specify That You Want To IE's Proxy Settings</p> <p>/// </ summary></p> <p>Public String ProxyAddress</p> <p>... {</p> <p>Get ... {return this.cproxyaddress;}</p> <p>Set ... {this.cproxyaddress = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// SEMICOLON SEPARATED Address List of the Servers The Proxy is not buy for.</p> <p>/// </ summary></p> <p>Public String ProxybyPass ... {</p> <p>Get ... {return this.cproxybypass;}</p> <p>Set ... {this.cproxyBypass = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// UserName for a password validating proxy. Only Used if the proxy info is set.</p> <p>/// </ summary></p> <p>Public String ProxyuserName</p> <p>... {</p> <p>Get ... {return this.cproxyusername;</p> <p>Set ... {this.cproxyusername = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Password for a password validating proxy. Only Used if the proxy info is set.</p> <p>/// </ summary></p> <p>Public String ProxyPassword</p> <p>... {</p> <p>Get ... {return this.cproxypassword;}</p> <p>Set ... {this.cproxypassword = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Timeout for the Web Request in Seconds. Times Out on Connection, Read and Send Operations.</p> <p>/// default is 30 seconds.</p> <p>/// </ summary></p> <p>Public int Timeout</p> <p>... {</p> <p>Get ... {return this.nconnecttimeout;</p> <p>Set ... {this.nconnecttimeout = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Error Message if The error flag is set or an error value is returned from a method.</p> <p>/// </ summary></p> <p>Public String ErrorMSG</p> <p>... {</p> <p>Get ... {return this.cerrormsg;}</p> <p>Set ... {this.cerrormsg = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// error flag if an error occurred.</p> <p>/// </ summary></p> <p>Public Bool Error</p> <p>... {</p> <p>Get ... {return this.berror;</p> <p>Set ... {this.berror = value;}</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// DETERMINES WHETER ERRORS CAUSE EXCEPTIONS to Be Thrown. By Default Errors</p> <p>/// Are Handled in the class and the error profifts.</p> <p>/// (Not Implement At this Time).</p> <p>/// </ summary></p> <p>Public Bool ThrowExceptions</p> <p>... {</p> <p>Get ... {return bthrowexception;</p> <p>Set ... {this.bthrowexceptions = value;</p> <p>}</p> <p>/ ** //// <summary></p> <p>////I set to a non-Zero Value Will Automatic or TRACK Cookies. The number assigned is the cookie count./// </ summary></p> <p>Public Bool Handlecookies</p> <p>... {</p> <p>Get ... {return this.bhandlecookies;</p> <p>Set ... {this.bHandlecookies = value;</p> <p>}</p> <p>Public cookiecollection cookies ... {</p> <p>Get ... {Return this.ocookies;</p> <p>Set ... {this.cookies = value;</p> <p>}</p> <p>Public httpwebresponsewebresponse ... {</p> <p>Get ... {Return this.OWebResponse;</p> <p>Set ... {this.oWebResponse = value;</p> <p>}</p> <p>Public httpwebrequest WebRequest ... {</p> <p>Get ... {return this.owebrequest;}</p> <p>Set ... {this.owebrequest = value;</p> <p>}</p> <p>// *** MEMBER Properties</p> <p>// String cpostbuffer = ""</p> <p>MemoryStream OpostStream;</p> <p>BinaryWriter OpostData;</p> <p>INT NPOSTMODE = 1;</p> <p>INT nConnectTimeout = 30;</p> <p>String CUSERAGENT = "West Wind http .net";</p> <p>String cusername = "";</p> <p>String CPassword = ""</p> <p>String cproxyaddress = ""</p> <p>String cproxybypass = ""</p> <p>String cproxyusername = "";</p> <p>String cproxypassword = ""</p> <p>Bool bthrowexceptions = false;</p> <p>Bool bhandlecookies = false;</p> <p>String cerrormsg = ""</p> <p>Bool Berror = false;</p> <p>HTTPWebResponse OweBRESPONSE</p> <p>HttpWebrequest OwebRequest;</p> <p>Cookiecollection Ocookies;</p> <p>String cmultipartboundary = "--------------------------- 7CF2A327F01AE";</p> <p>Public void wwhttp ()</p> <p>... {</p> <p>//</p> <p>// Todo: add constructor logic here</p> <p>//</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Adds post form variables to the request buffer.</p> <p>/// httppostmode determines how Parms Are Handled.</p> <p>/// 1 - Urlencoded Form Variables. Uses key and value pairs (IE. "Name", "rick") to create urlencoded Content</p> <p>/// 2 - Multi-Part Forms - Not supported</p> <p>/// 4 - XML ​​block - Post a Single XML Block. Pass in as key (1st Parm)</p> <p>/// other - raw content buffer. Just assign to key.</p> <p>/// </ summary></p> <p>/// <param name = "key"> Key value or raw buffer depending on post type </ param></p> <p>/// <param name = "value"> Value to store. Used Only In Key / Value Pair Modes </ param></p> <p>Public void addpostkey (String Key, Byte [] Value)</p> <p>... {</p> <p>IF (this.opostdata == null)</p> <p>... {</p> <p>This.opostStream = new memorystream ();</p> <p>this.opostdata = new binarywriter (this.opostStream);</p> <p>}</p> <p>IF (key == "reset")</p> <p>... {</p> <p>This.opostStream = new memorystream ();</p> <p>this.opostdata = new binarywriter (this.opostStream);</p> <p>}</p> <p>Switch (this.npostmode)</p> <p>... {</p> <p>Case 1:</p> <p>This.opostData.write (Encoding.Getencoding (1252) .Getbytes</p> <p>Key "=" System.Web.httputility.urlencode "&"));</p> <p>Break;</p> <p>Case 2:</p> <p>This.opostData.write (Encoding.Getencoding (1252) .Getbytes</p> <p>"-" this.cmultipartboundary "/ r / n" </p> <p>"Content-Disposition: Form-Data; Name = /" " Key " / "/ r / n / r / n"))</p> <p>This.opostData.write (value);</p> <p>This.opostData.write (Encoding.Getencoding (1252) .Getbytes ("/ r / n"));</p> <p>Break;</p> <p>DEFAULT:</p> <p>This.opostData.write (value);</p> <p>Break;</p> <p>}</p> <p>}</p> <p>Public Void AddPostKey (String Key, String Value)</p> <p>... {</p> <p>THIS.AddPostKey (key, encoding.getencoding (1252) .getbytes (value));</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Adds a fully self Contained Post Buffer To The Request.</p> <p>/// Works for xml or previously encoded content.</p> <p>/// </ summary></p> <p>/// <param name = "posbuffer"> </ param></p> <p>Public void AddPostKey (String FullPostBuffer)</p> <p>... {</p> <p>This.opostData.write (Encoding.Getencoding (1252) .Getbytes (fullpostbuff);}</p> <p>Public Bool AddPostfile (String Key, String Filename)</p> <p>... {</p> <p>LCFILE;</p> <p>IF (this.npostmode! = 2) ... {</p> <p>this.cerrormsg = "File Upload Allowed Only with Multi-Part Forms";</p> <p>THIS.BERROR = True;</p> <p>Return False;</p> <p>}</p> <p>Try</p> <p>... {</p> <p>FileStream Lofile = New FileStream (filename, system.io.filemode.open, system.io.fileAccess.read);</p> <p>Lcfile = New byte [Lofile.Length];</p> <p>Lofile.read (lcfile, 0, (int) Lofile.Length);</p> <p>Lofile.Close ();</p> <p>}</p> <p>Catch (Exception E)</p> <p>... {</p> <p>THIS.CERRORMSG = E.MESSAGE;</p> <p>THIS.BERROR = True;</p> <p>Return False;</p> <p>}</p> <p>This.opostData.write (Encoding.Getencoding (1252) .Getbytes</p> <p>"-" this.cmultipartboundary "/ r / n" </p> <p>"Content-Disposition: Form-Data; Name = /" Key "/" filename = / "" </p> <p>New fileInfo (filename) .Name "/" / r / n / r / n "))))</p> <p>This.opostData.write (lcfile);</p> <p>This.opostData.write (Encoding.Getencoding (1252) .Getbytes ("/ r / n"));</p> <p>Return True;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Return A The Result from an HTTP URL INTO A streamreader is STREAMReader.</p> <p>/// Client Code Should Call Close () on The Returned Object When Done Reading.</p> <p>/// </ summary></p> <p>/// <param name = "URL"> URL TO RETRIEVE. </ param></p> <p>/// <param name = "WebRequest"> An HttpWebRequest Object That Can Be Passed in With Properties PRESET. </ param></p> <p>/// <returns> </ returns></p> <p>Protected StreamReader getURLstream (String Url, HttpWebRequest Request)</p> <p>... {</p> <p>Try</p> <p>... {</p> <p>THIS.BERROR = FALSE;</p> <p>THIS.CERRORMSG = ""</p> <p>IF (Request == NULL)</p> <p>... {Request = (httpwebrequest) System.Net.WebRequest.create (URL);} Request.USERAGENT = this.cusenergy</p> <p>Request.timeout = this.nConnectTimeout * 1000;</p> <p>// *** save for external access</p> <p>This.owebRequest = Request;</p> <p>// *** Handle Security for the Request</p> <p>IF (this.cusername.length> 0)</p> <p>... {IF (this.cusername == "autological") Request.credentials = CredentialCache.defaultcredentials; else request.credentials = new networkcredential (this.cusername, this.cpassword);}</p> <p>// *** Handle Proxy Server Configuration</p> <p>IF (this.cproxyaddress.length> 0)</p> <p>... {if (this.cproxyaddress == "defaultproxy") ... {Request.Proxy = new webproxy (); request.proxy = WebProxy.getDefaultProxy ();} else ... {WebProxy loProxy = new webproxy This.cproxyaddress, true); if (this.cproxybypass.Length> 0) ... {loProxy.bypasslist = this.cproxybyPass.split (';');} if (this.cproxyusername.length> 0) loProxy.credentials = New NetworkCredential (this.cproxyusername, this.cproxypassword); Request.Proxy = loproxy;}}</p> <p>// *** Handle Cookies - Automatical RE-Assign</p> <p>IF (this.bHandlecookies)</p> <p>... {Request.cookieContainer = New cookieContainer (); if (this.ocookies! = Null && this.ocookies.count> 0) ... {Request.cookieContainer.add (this.ocookies);}}</p> <p>// *** DEAL with the post buffer if any one</p> <p>IF (this.opostdata! = null)</p> <p>... {Request.Method = "post"; switch (this.npostmode) ... {case 1: request.contenttype = "Application / X-www-form-urlencoded"; // Strip Off ANY Trailing & Which CAN Cause problems with some // http servers //iff (this.cpostbuffer.endswith ("&") // this.cpostbuffer = this.cpostbuffer.substring (0, this.cpostbuffer.Length-1); break; case 2 : Request.contentType = "Multipart / Form-Data; Boundary =" this.cmultipartBoundary; this.opostData.write (Encoding.Getencoding (1252) .Getbytes ("-" this.cmultipartBoundary "/ r / n" )); break; case 4: request.contentType = "text / xml"; break; default: goto case 1;} stream lopostdata = request.getRequestStream (); //lopostData.write (LCPostData ,0 ,lcpostdata.length) ; this.oPostStream.WriteTo (loPostData); byte [] buffer = new byte [this.oPostStream.Length]; buffer = this.oPostStream.ToArray (); Console.Write (Encoding.GetEncoding (1252) .GetString (buffer, 0, Buffer.Length); // *** Close The Memory Stream this.opostStream.close (); this.o Poststream = NULL; // *** Close the binary writer this.opostdata.close (); this.opostdata = null; // *** Close Request stream lopostdata.close (); // *** Clear the post buffer //this.cpostbuffer = "" "" // *** Retrieve The Response Headers</p> <p>HTTPWebResponse response = (httpwebresponse) Request.getResponse ();</p> <p>// ** save cookies the Server sends</p> <p>IF (this.bHandlecookies)</p> <p>... {if (response.cookies.count> 0) ... {if (this.ocookies == null) ... {this.ocookies = response.cookies;} else ... {// ** if we already have cookies update the list foreach (Cookie oRespCookie in Response.Cookies) ... {bool bMatch = false; foreach (Cookie oReqCookie in this.oCookies) ... {if (oReqCookie.Name == oRespCookie.Name). .. {OreqCookie.Value = orespcookie.name; bmatch = true; break; //}} // for Each ReqCookies if (! bmatch) this.ocookies.Add (ORESPCOOKIE);} // for each response.cookies} / / this.cookies == null} // if Response.cookie.count> 0} // if this.bHandlecookies = 0 // *** save the response object for External Access</p> <p>This.OweBResponse = response;</p> <p>ENCODING ENC;</p> <p>Try</p> <p>... {if (response.contentencoding.Length> 0) ENC = Encoding.Getencoding; else enc = encoding.getencoding (1252);</p> <p>Catch</p> <p>... {// *** invalid Encoding passed enc = encoding.getencoding (1252);</p> <p>// *** Drag to a stream</p> <p>StreamReader strretponse =</p> <p>NEW streamreader (response.getresponsestream (), eNC);</p> <p>Return Strresponse;</p> <p>}</p> <p>Catch (Exception E)</p> <p>... {</p> <p>IF (this.bthrowexception)</p> <p>Throw e;</p> <p>THIS.CERRORMSG = E.MESSAGE;</p> <p>THIS.BERROR = True;</p> <p>Return NULL;</p> <p>}</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Return A The Result from an HTTP URL INTO A streamreader is STREAMReader.</p> <p>/// Client Code Should Call Close () on The Returned Object When Done Reading.</p> <p>/// </ summary></p> <p>/// <param name = "URL"> URL TO RETRIEVE. </ param></p> <p>/// <returns> </ returns></p> <p>Public StreamReader getURLstream (String URL)</p> <p>... {</p> <p>Httpwebrequest = null;</p> <p>Return this.geturlStream (URL, OHTTPWebRequest);</p> <p>}</p> <p>/ ** //// <summary> /// Return A The Result from an HTTP URL INTO A streamreader.</p> <p>/// Client Code Should Call Close () on The Returned Object When Done Reading.</p> <p>/// </ summary></p> <p>/// <param name = "request"> a Request Object </ param></p> <p>/// <returns> </ returns></p> <p>Public StreamReader getURLStream (httpwebrequest request)</p> <p>... {</p> <p>Return this.geturlstream (Request.Requesturi.absoluteuri, request);</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Return a the result from an HTTP URL INTO A STRING.</p> <p>/// </ summary></p> <p>/// <param name = "URL"> URL TO RETRIEVE. </ param></p> <p>/// <returns> </ returns></p> <p>Public String getURL (String URL)</p> <p>... {</p> <p>StreamReader OHTTPRESPRESPONSE = this.geturlstream (URL);</p> <p>IF (OHTTPRESPONSE == NULL)</p> <p>""; "</p> <p>String lcResult = OHTTPRESPONSE.READTOEND ();</p> <p>OhttpResponse.close ();</p> <p>Return LCRESULT;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Return a the result from an HTTP URL INTO A STRING.</p> <p>/// </ summary></p> <p>/// <param name = "URL"> URL TO RETRIEVE. </ param></p> <p>/// <returns> </ returns></p> <p>Public Byte [] geturlbytes (String URL)</p> <p>... {</p> <p>StreamReader OHTTPRESPRESPONSE = this.geturlstream (URL);</p> <p>IF (OHTTPRESPONSE == NULL)</p> <p>... {</p> <p>Return NULL;</p> <p>}</p> <p>String lcResult = OHTTPRESPONSE.READTOEND ();</p> <p>OhttpResponse.close ();</p> <p>Return NULL;</p> <p>}</p> <p>/ ** //// <summary></p> <p>/// Retrieves URL with events in the onreceivedata event.</p> <p>/// </ summary></p> <p>/// <param name = "URL"> </ param></p> <p>/// <param name = "buffersize"> </ param></p> <p>/// <returns> </ returns></p> <p>Public String GeturLevents (String Url, long buffersize)</p> <p>... {</p> <p>StreamReader OHTTPRESPRESPONSE = this.geturlstream (URL);</p> <p>IF (OHTTPRESPONSE == NULL) RETURN ""</p> <p>Long lnsize = buffersize;</p> <p>IF (this.OWebResponse.contentLength> 0)</p> <p>Lnsize = this.oWebResponse.contentLength;</p> <p>Else</p> <p>Lnsize = 0;</p> <p>Encoding enc = encoding.getencoding (1252);</p> <p>Stringbuilder Lowriter = New StringBuilder ((int) lnsize);</p> <p>Char [] lcTemp = new char [buffersize];</p> <p>OnreceiveDataEventArgs OARGS = New OnreceiveDataEventAeventArgs ();</p> <p>OARGS.TOTALBYTES = LNSIZE;</p> <p>LNSIZE = 1;</p> <p>INT LNCOUNT = 0;</p> <p>Long lntotalbytes = 0;</p> <p>While (lnsize> 0)</p> <p>... {</p> <p>Lnsize = OHTTPRESPONSE.READ (lcTemp, 0, (int) buffersize;</p> <p>IF (lnsize> 0)</p> <p>... {Lowriter.Append (lcTemp, 0, (int) lnsize); lncount ; lntotalbytes = lnsize; // *** raise an Event if hooked Up if (this.onReceiveData! = null) ... {/ ** //// *** Update the event handler oArgs.CurrentByteCount = lnTotalBytes; oArgs.NumberOfReads = lnCount; oArgs.CurrentChunk = lcTemp; this.OnReceiveData (this, oArgs); // *** Check for cancelled flag if (OARGS.CANCEL) goto closed-;}}</p> <p>} // while</p> <p>Closedown:</p> <p>OhttpResponse.close ();</p> <p>// *** Send Done Notification</p> <p>IF (this.onreceivedata! = null&&! oargs.cancel)</p> <p>... {</p> <p>// *** Update The Event Handler</p> <p>OARGS.DONE = true;</p> <p>THIS.ONRECEIVEDATA (THIS, OARGS);</p> <p>}</p> <p>// Return LCHTML;</p> <p>Return Lowriter.toString ();</p> <p>}</p> <p>Public Delegate Void OnReceiDataHandler (Object Sender, OnreceiveDataEventArgs E);</p> <p>Public Class OnRecEiveDataEventAeventAeventArgs</p> <p>... {</p> <p>Public long currentBytecount = 0;</p> <p>Public long Totalbytes = 0;</p> <p>Public int numBerofreads = 0;</p> <p>Public char [] Currentchunk;</p> <p>Public bool done = false;</p> <p>Public Bool Cancel = False;</p> <p>}</p> <p>}</p> <p>In WWHTTP, you can transfer the file addpostfile method, but also transfer the variable addpostKey method. This way, if we want to transfer files through the proxy server, you can write the following code:</p> <p>WWHTTP WW</p> <p>=</p> <p>New</p> <p>WWHTTP ();</p> <p>Ww.ProxyAddress</p> <p>=</p> <p>"</p> <p>202.132.156.124</p> <p>"</p> <p>;</p> <p>WW.POSTMODE</p> <p>=</p> <p>2</p> <p>;</p> <p>Ww.addpostKey</p> <p>"</p> <p>TestKey</p> <p>"</p> <p>,</p> <p>"</p> <p>Test</p> <p>"</p> <p>);</p> <p>ww.addpostfile</p> <p>"</p> <p>Myfile</p> <p>"</p> <p>,</p> <p>@ "</p> <p>D: /Temp/java/javast/javastart2.jar</p> <p>"</p> <p>);</p> <p>String</p> <p>SHTML</p> <p>=</p> <p>WW.GeturLevents</p> <p>"</p> <p>http://localhost/uploadfileweb/webform1.aspx</p> <p>"</p> <p>,</p> <p>409600</p> <p>);</p> <p>Console.write (SHTML);</p> <p>summary:</p> <p>(</p> <p>1</p> <p>) By the web services.</p> <p>(</p> <p>2</p> <p>) If you don't need to use a proxy, use the WebClient class</p> <p>(</p> <p>3</p> <p>) If you need a proxy, use the extension to get the class WWHTTP</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-71856.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="71856" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'qhEsWfqSXqN8PTdE16vDFUfPtCJg8B4819GMRoSQwM5YxO2hkWg3Qf7sGxqOcHA8Xfr2v4yu4QqtYOalG_2BFqBQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>