WebClient static page generation

Source: Internet
Author: User

A Brief Introduction to WebClient:
The WebClient class provides public methods for sending data to any local, Intranet, or Internet Resource identified by the URI and receiving data from these resources.
The WebClient class uses the webrequest class to provide access to resources. A WebClient instance can access data through any webrequest child that has been registered with the webrequest. registerprefix method.
Note:
By default,. NET Framework supports Uris starting with HTTP:, https:, ftp:, and file: Scheme identifier.

The following describes the WebClient method used to upload data to a resource:
Openwrite retrieves a stream used to send data to resources.
Openwriteasync retrieves stream, which sends data to resources without stopping the calling thread.
Uploaddata sends the byte array to the resource and returns the byte array containing any response.
Uploaddataasync sends the byte array to the resource without blocking the calling thread.
Uploadfile sends the local file to the resource and returns a byte array containing any response.
Uploadfileasync sends local files to resources without stopping the calling thread.
Uploadvalues sends the namevaluecollection to the resource and returns a byte array containing any response.
Uploadvaluesasync sends the namevaluecollection to the resource without blocking the calling thread, and returns a byte array containing any response.
Uploadstring sends the string to the resource without stopping the calling thread.
Uploadstringasync sends the string to the resource without stopping the calling thread.

The following describes the WebClient Method for downloading data from a resource:
Openread returns data from a resource in the form of stream.
Openreadasync returns data from the resource without blocking the call thread.
Downloaddata downloads data from the resource and returns the byte array.
Downloaddataasync downloads data from the resource and returns a byte array without stopping the calling thread.
Downloadfile downloads data from a resource to a local file.
Downloadfileasync downloads data from the resource to a local file without stopping the calling thread.
Downloadstring downloads the string from the resource and returns the string.
Downloadstringasync downloads the string from the resource without blocking the call thread.

You can use the cancelasync method to cancel unfinished asynchronous operations.
The WebClient instance does not send optional HTTP headers. If your request requires an optional Header, you must add it to the headers set. For example, to retain the query in the response, you must add the user proxy header. In addition, if the user proxy header is lost, the server may return 500 (internal server error ).
In the WebClient instance, allowautoredirect is set to true.
The description to the successor indicates that the derived class should call the basic class implementation of WebClient to ensure that the derived class works as expected.

Source code:

1. Using system;

2. Using system. Collections. Generic;

3. Using system. componentmodel;

4. Using system. Data;

5. Using system. drawing;

6. Using system. text;

7. Using system. Windows. forms;

8. Using system. net;

9. Using system. IO;

10.

11. namespace wiindowsformsapplication

12 .{

13. Public partial class form1: Form

14 .{

15. Public form1 ()

16 .{

17. initializecomponent ();

18. This. textbox1.text = @ "http://dl-sh-ocn-1.pchome.net/0d/bx/koomail50b8.rar ";

19 .}

20.

21. WebClient = new WebClient ();

22. Private void btn_down_click (Object sender, eventargs E)

23 .{

24.

25. If (WebClient. isbusy) // whether a Web request is in progress

26 .{

27. WebClient. cancelasync ();

28 .}

29. // Add events for WebClient

30. WebClient. downloadprogresschanged + = new downloadprogresschangedeventhandler (webclient_downloadprogresschanged );

31. WebClient. downloadfilecompleted + = new asynccompletedeventhandler (webclient_downloadfilecompleted );

32. // start download

33. WebClient. downloadfileasync (New uri (this. textbox1.text), "aa.rar ");

34 .}

35.

36. Private void webclient_downloadprogresschanged (Object sender, downloadprogresschangedeventargs E)

37 .{

38. This. progressbar1.value = E. progresspercentage;

39. This. lbl_pro.text = E. progresspercentage. tostring () + "% ";

40. This. lbl_detail.text = string. Format ("downloading file, progress {0}/{1} (bytes )"

41., E. bytesreceived

42., E. totalbytestoreceive );

43 .}

44.

45. Private void webclient_downloadfilecompleted (Object sender, asynccompletedeventargs E)

46 .{

47. If (E. cancelled)

48. MessageBox. Show ("Download canceled! ");

49. Else

50. MessageBox. Show ("Download complete! ");

51 .}

52.

53. Private void btn_cancel_click (Object sender, eventargs E)

54 .{

55. This. WebClient. cancelasync ();

56. This. WebClient. Dispose ();

57 .}

58 .}

59 .}

WebClient generates static pages

// <Summary>
/// Generate the html version.
/// </Summary>
/// <Param name = "url"> Generate an address </param>
Public void getremotehtmlcode (string filepath, string URL)
{
WebClient mywebclient = newwebclient ();
Mywebclient. Credentials = credentialcache. defaultcredentials;
Byte [] pagedata = mywebclient. downloaddata (URL );
String mydatabuffer = encoding. utf8.getstring (pagedata );

// Remove viewstate
// String pattern = @ "<inputtype =" "hidden" "name =" "_ viewstate" "id = [^>] (? <View> [^>] *)> ";
String Pattern = @ "<inputtype =" "hidden" "name =" "_ viewstate" "id = [^>] [^>] *> ";

System. Text. regularexpressions. RegEx Reg = Newsystem. Text. regularexpressions. RegEx (pattern, system. Text. regularexpressions. regexoptions. ignorecase );
Mydatabuffer = reg. Replace (mydatabuffer ,"");
Encoding code = encoding. utf8;
// Write an object
Streamwriter Sw = NULL;
Try
{
Sw = newstreamwriter (filepath, false, Code );
Sw. writeline (mydatabuffer );
Sw. Flush ();
Response. Write ("OK ");
}
Catch (exception ex)
{
// File. Delete (path + htmlfilename );
Httpcontext. Current. response. Write (ex. Message );
Httpcontext. Current. response. End ();
Response. Write ("no ");
}
Finally
{
If (SW! = NULL)
Sw. Close ();
}
}

Aspx generate static html pages (WebClient method)

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. net;
Using system. text;
Using system. IO;

Public partial class: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{

}
Public streamwriter SW;
Protected void button#click (Object sender, eventargs E)
{
WebClient mywebclient = new WebClient ();

Mywebclient. Credentials = credentialcache. defaultcredentials;

Byte [] pagedata = mywebclient. downloaddata ("http: //" + request. servervariables ["http_host"]. tostring () + "/dl_food_ui/food_web/dongshouye. aspx ");

String mydatabuffer = encoding. utf8.getstring (pagedata );

String Path = httpcontext. Current. server. mappath ("./food_web /");

Encoding code = encoding. getencoding ("UTF-8 ");

String htmlfilename = "foodindex.htm ";

Try
{
Sw = new streamwriter (path + htmlfilename, false, Code );

Sw. writeline (mydatabuffer );

Sw. Flush ();

Response. Write ("generated successfully! OK ");

}
Catch (exception ex)
{
File. Delete (path + htmlfilename );
Httpcontext. Current. response. Write (ex. Message );
Httpcontext. Current. response. End ();

Response. Write ("generation failed! No ");
}
Finally
{
If (SW! = NULL)

Sw. Close ();
}
}
Protected void button2_click (Object sender, eventargs E)
{
Response. Redirect ("./food_web/dongshouye. aspx ");
}
Protected void button3_click (Object sender, eventargs E)
{
Response. Redirect ("./food_web/foodindex.htm ");
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.