Login to Blog Park (get/post) in C # using System.Net.Http.HttpClient emulation

Source: Internet
Author: User

OneSystem.Net.Http. HttpClient Introduction

System.Net.Http is the programming interface for HTTP applications introduced in Microsoft net4.5, which Microsoft calls "modern HTTP programming Interfaces", which mainly provide the following:

1. Users use the modern Web Service client components via HTTP;

2. HTTP components that can be used concurrently on both the client and the server (such as processing HTTP headers and messages) provide a consistent programming model for both the client and the server.

Personally, it seems to be plagiarism Apache HTTP client, the current online people do not seem to be many, the personal think that the greatest advantage of using httpclient is: Do not have to manage their own cookies, as long as the responsibility to write a good request.

Due to the lack of information on the Internet, this is a simple summary of the usage of the Get and post requests by logging into the blog site.

View the Microsoft API to discover its properties method: Http://msdn.microsoft.com/zh-cn/library/system.net.http.httpclient.aspx

It can be seen by its API that if you want to set the request header , you only need to set it in Defaultrequestheaders.

Create Httpcliet can be directly new HttpClient ()

send requests can call their methods, such as get call Getasync (URI),Post calls Postasync (URI, httpcontent), and so on, in the way that they are sent ...

Second, example (Analog post login Blog Park)

First, it is necessary to note that this instance environment is Win7 64-bit +vs 2013+. NET 4.5 framework.

1. Use vs2013 to create a new console program, or a form program, as shown in:

2. The System.Net.Http framework must be introduced, otherwise you will not be able to use httpclient

3. Implementing the Code
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net.Http;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Threading.Tasks;namespaceclasslibrary1{ Public classClass1 {Private StaticString dir =@"C:\work\"; /// <summary>        ///write files to local/// </summary>        /// <param name= "FileName" ></param>        /// <param name= "html" ></param>         Public Static voidWrite (stringFileName,stringhtml) {            Try{FileStream fs=NewFileStream (dir +FileName, FileMode.Create); StreamWriter SW=NewStreamWriter (FS, Encoding.default); Sw.                Write (HTML); Sw.                Close (); Fs.            Close (); }Catch(Exception ex) {Console.WriteLine (ex).            StackTrace); }                   }        /// <summary>        ///write files to local/// </summary>        /// <param name= "FileName" ></param>        /// <param name= "html" ></param>         Public Static voidWrite (stringFileName,byte[] HTML) {            Try{file.writeallbytes (dir+fileName, HTML); }            Catch(Exception ex) {Console.WriteLine (ex).            StackTrace); }                    }        /// <summary>        ///Log in to Blog Park/// </summary>         Public Static voidlogincnblogs () {HttpClient HttpClient=NewHttpClient (); Httpclient.maxresponsecontentbuffersize=256000; HTTPCLIENT.DEFAULTREQUESTHEADERS.ADD ("user-agent","mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/36.0.1985.143 safari/537.36"); String URL="http://passport.cnblogs.com/login.aspx"; Httpresponsemessage Response= Httpclient.getasync (NewUri (URL)).            Result; String result=Response. Content.readasstringasync ().            Result; String username="Hi_amos"; String Password=the password";  Do{String __eventvalidation=NewRegex ("id=\ "__eventvalidation\" value=\ "(. *?) \""). Match (Result). groups[1].                Value; String __viewstate=NewRegex ("id=\ "__viewstate\" value=\ "(. *?) \""). Match (Result). groups[1].                Value; String Lbd_vcid_c_login_logincaptcha=NewRegex ("id=\ "Lbd_vcid_c_login_logincaptcha\" value=\ "(. *?) \""). Match (Result). groups[1].                Value; //Image Verification CodeURL ="http://passport.cnblogs.com"+NewRegex ("id=\ "c_login_logincaptcha_captchaimage\" src=\ "(. *?) \""). Match (Result). groups[1].                Value; Response= Httpclient.getasync (NewUri (URL)).                Result; Write ("Amosli.png", Response. Content.readasbytearrayasync ().                                Result); Console.WriteLine ("Enter a picture verification code:"); String Imgcode="Wupve";//The verification code is written locally and needs to be filled in manually.Imgcode =Console.ReadLine (); //Start LoginURL ="http://passport.cnblogs.com/login.aspx"; List<keyvaluepair<string, string>> paramlist =NewList<keyvaluepair<string, string>>(); Paramlist.add (Newkeyvaluepair<string,string> ("__eventtarget","")); Paramlist.add (Newkeyvaluepair<string,string> ("__eventargument","")); Paramlist.add (Newkeyvaluepair<string,string> ("__viewstate", __viewstate)); Paramlist.add (Newkeyvaluepair<string,string> ("__eventvalidation", __eventvalidation)); Paramlist.add (Newkeyvaluepair<string,string> ("Tbusername", username)); Paramlist.add (Newkeyvaluepair<string,string> ("Tbpassword", password)); Paramlist.add (Newkeyvaluepair<string,string> ("Lbd_vcid_c_login_logincaptcha", Lbd_vcid_c_login_logincaptcha)); Paramlist.add (Newkeyvaluepair<string,string> ("Lbd_backworkaround_c_login_logincaptcha","1")); Paramlist.add (Newkeyvaluepair<string,string> ("Captchacodetextbox", Imgcode)); Paramlist.add (Newkeyvaluepair<string,string> ("Btnlogin","Login")); Paramlist.add (Newkeyvaluepair<string,string> ("Txtreturnurl","http://home.cnblogs.com/")); Response= Httpclient.postasync (NewUri (URL),Newformurlencodedcontent (paramlist)).                Result; Result=Response. Content.readasstringasync ().                Result; Write ("mycnblogs.html", result); }  while(result.) Contains ("Verification Code Error, please re-enter")); Console.WriteLine ("Login Successful! "); //Run out and remember to releaseHttpclient.dispose (); }         Public Static voidMain () {logincnblogs (); }}

Code Analysis:

First, start with the main function and call the Logincnblogs method;

Second, use the Get method:

Httpclient.getasync (new   Uri (URL)). Result; = Response. Content.readasstringasync (). Result;

Furthermore, using the Post method:

  list<keyvaluepair<string, string>> paramlist = new                 list<keyvaluepair<string, String>> (); Paramlist.add ( new  keyvaluepair< String , "  __eventtarget  ,  " Span style= "color: #000000;"  > ));                ....  Response    = Httpclient.postasync (new  Uri (URL),     Formurlencodedcontent (paramlist)).                Result;  Result  = Response. Content.readasstringasync (). Result; 

Finally, Note that the return value can be either a string or a byte[], and the way the stream is, see what you need here.

4. After the successful login

1). After using the browser login:

2). After logging in with Httpcliet:

In summary, it can be found that the usage of httpclient in C # is very similar to that in Java, so it is true that plagiarism is not too much.

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.