. NET provides class libraries that use various network protocols to access networks and the Internet.
1. WebClient class
If you only want to read files from a website, it is enough to use the WebClient class. It can execute some basic operations through one or two simple commands. It is easy to use. Create a winform project, add the ListBox control, and read the content on the Baidu page. The WebClient class also supports the uploadfile and uploaddata methods to upload files.
Sample Code:
Public form1 ()
{
Initializecomponent ();
System. net. WebClient client = new WebClient (); // create a client
Stream STRM = client. openread ("http://www.baidu.com"); // create a read stream
Streamreader sr = new streamreader (STRM );
String line;
While (line = Sr. Readline ())! = NULL)
{
Listbox1.items. Add (line );
}
STRM. Close (); // close the stream
}
2. webrequest class and webresponse class
The WebClient class is easy to use, but it cannot be used to provide an authentication certificate. When using it to upload files, many websites do not receive files uploaded without authentication. Moreover, WebClient can use any protocol to receive and send requests, so that it cannot process cookie information similar to HTTP. To use these features, you must use the webrequest class and webresponse class.
Example of obtaining HTTP title information:
Webrequest WRQ = webrequest. Create ("http://www.baidu.com ");
Httpwebrequest hwrq = (httpwebrequest) WRQ;
Listbox1.items. Add ("request timeout (MS) =" + WRQ. Timeout );
Listbox1.items. Add ("request Keep Alive =" + hwrq. keepalive );
Listbox1.items. Add ("request allowautoredirect =" + hwrq. allowautoredirect );
Listbox1.items. Add ("\ r \ n ");
Webresponse WRS = WRQ. getresponse ();
Webheadercollection WHC = WRS. headers;
For (INT I = 0; I <WHC. Count; I ++)
{
Listbox1.items. Add ("Header" + WHC. getkey (I) + ":" + WHC [I]);
}
Use authentication: attach a value to the credentials of WRQ before getresponse, as shown below,
Networkcredential mycred = new networkcredential ("myusername", "mypassword ");
WRQ. Credentials = mycred;
Asynchronous page request:
Public form1 ()
{
Initializecomponent ();
Webrequest WRQ = webrequest. Create ("http://www.baidu.com ");
WRQ. begingetresponse (New asynccallback (onresponse), WRQ); // Asynchronous Start request, the onresponse method actually responds to the request
}
Protected void onresponse (iasyncresult AR)
{
Webrequest WRQ = (webrequest) Ar. asyncstate;
Webresponse WRS = WRQ. endgetresponse (AR );
// To do read
}
3. display the output result as an HTML page. The magic webbrowser class
The webbrowser class allows you to navigate the webpage in the form, which has many attributes of ie available, and can also operate the content of the webpage through the document attribute.
Webbrowser. navigate ("access address") to load the webpage to be accessed. It also supports forward and backward operations.