Common Web pages get page content using WebRequest or HttpWebRequest to manipulate Http requests.
For example, get the HTML page of Baidu website
varRequest = WebRequest.Create ("http://www.baidu.com"); Request. Method="GET"; varResponse =request. GetResponse (); using(varstream =NewSystem.IO.StreamReader (response. GetResponseStream ())) {varContent = stream. ReadToEnd ();//gets the page string to the remoteConsole.WriteLine (content); }
POST Request
varJsontopost ="{\ "name\": \ "admin\", \ "pwd\": \ "123456\"}"; varRequest = WebRequest.Create ("http://www.sina.com"); Request. Method="POST"; using(varRequeststream =request. GetRequestStream ()) {varbytes =Encoding.UTF8.GetBytes (jsontopost); requestStream.Write (Bytes,0, Bytes. Length); } varResponse =request. GetResponse (); using(varstream =NewSystem.IO.StreamReader (response. GetResponseStream ())) {varContent = stream. ReadToEnd ();//get Post-returned content}
There is a way to request, that is httpclient this way, this way is not common, but compared to the above approach is relatively concise, a code is definitely a good way to achieve.
using (varnew HttpClient ()) { var content= http. Getasync ("http://www.baidu.com"). Getawaiter (). GetResult () . Content.readasstringasync (). Getawaiter (). GetResult (); }
POST request
using (varnew HttpClient ()) { var"{\" name\ ": \" admin\ ", \" pwd\ ": \" 123456\ "}"; var content = http. Postasync ("http://www.baidu.com"new stringcontent (jsontopost)) . Getawaiter (). GetResult () . Content.readasstringasync (). Getawaiter (). GetResult (); }
If there is a better way to follow up welcome everyone to exchange learning!
C # Several ways to get page content