C # Several ways to get page content

Source: Internet
Author: User

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

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.