1. WebClient class
In the system. Net Space, classes are provided to send data to the target of the URI identifier and receive data from the target of the URI identifier.
Openreadcompleted
Private void dowebclient ()
{
String url = "http://www.qq.com ";
WebClient client = new WebClient ();
Client. openreadasync (New uri (URL ));
Client. openreadcompleted + = new openreadcompletedeventhandler (webclient_openreadcompleted );
}
Private void webclient_openreadcompleted (Object sender, openreadcompletedeventargs E)
{
Using (streamreader reader = new streamreader (E. Result, dbcscodepage. dbcsencoding. getdbcsencoding ("gb2312 ")))
{
String contents = reader. readtoend ();
Int begin = contents. tostring (). indexof ("<title> ");
Int end = contents. tostring (). indexof ("</title> ");
// UI thread call to directly update the interface
Clienttext. Text = contents. tostring (). substring (begin + 7, end-begin-7 );
}
}
2. httpwebrequest class
Provides the http implementation of the webrequest class in the system. Net Space.
Private void dohttpwebrequest ()
{
String url = "http://www.baidu.com ";
Webrequest request = httpwebrequest. Create (URL );
Iasyncresult result = request. begingetresponse (responsecallback, request );
}
Private void responsecallback (iasyncresult result)
{
Httpwebrequest Req = result. asyncstate as httpwebrequest;
Webresponse res = Req. endgetresponse (result );
Using (Stream stream = res. getresponsestream ())
Using (streamreader reader = new streamreader (stream, dbcscodepage. dbcsencoding. getdbcsencoding ("gb2312 ")))
{
String contents = reader. readtoend ();
Int begin = contents. tostring (). indexof ("<title> ");
Int end = contents. tostring (). indexof ("</title> ");
// Runs based on the background, not in the UI thread
Dispatcher. begininvoke () =>{ reqtext. Text = contents. tostring (). substring (begin + 7, end-begin-7 );});
}
}
PS: dbcscodepage is used to solve the garbled problem.
Source code: http://download.csdn.net/detail/wulongtiantang/5072852