C # using the System.Net.Http.HttpClient Analog login Blog Park (get/post)

Source: Internet
Author: User

Original link: http://www.cnblogs.com/amosli/p/3918538.html

introduction of System.Net.Http.HttpClient

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. Client components for users using modern Web service via HTTP;

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

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

By its API you can see 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 individually, such as Get call Getasync (URI),post call Postasync (URI, httpcontent), and so forth ...

Ii. Examples (analog post login Blog Park)

First, it needs to be explained that this instance environment is the 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 the following illustration:

2. You must introduce the SYSTEM.NET.HTTP framework, otherwise you will not be able to use httpclient

3. Implementation code

Using System;
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Net.Http;
Using System.Text;
Using System.Text.RegularExpressions;

Using System.Threading.Tasks;

        Namespace ClassLibrary1 {public class Class1 {private static String dir = @ "C:\work\"; <summary>///write files to local///</summary>///<param name= "FileName" ></param&gt
        ;
            <param name= "html" ></param> public static void Write (string fileName, string html) {
                try {FileStream fs = new FileStream (dir + fileName, FileMode.Create);
                StreamWriter sw = New StreamWriter (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 void Write (String fileName, byte[] html) {try {
            File.writeallbytes (dir + fileName, html); The catch (Exception ex) {Console.WriteLine (ex).
            StackTrace);  }}///<summary>///login Blog Park///</summary> public static
            void Logincnblogs () {httpclient httpclient = new HttpClient ();
            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 (new Uri (URL)).
            result; String result = Response. Content.readasstringasync ().

            result;
            String username = "Hi_amos";

            String password = "password"; do {String __eventvalidation = new Regex ("id=\" __eventvalidation\ "value=\" (. *?) \""). Match (Result). GROUPS[1].
                Value; String __viewstate = new Regex ("id=\" __viewstate\ "value=\" (. *?) \""). Match (Result). GROUPS[1].
                Value; String Lbd_vcid_c_login_logincaptcha = new Regex ("id=\" Lbd_vcid_c_login_logincaptcha\ "value=\" (. *?) \""). Match (Result). GROUPS[1].

                Value; Picture Verification Code URL = "http://passport.cnblogs.com" + New Regex ("id=\" c_login_logincaptcha_captchaimage\ "src=\" (. *?) \""). Match (Result). GROUPS[1].
                Value; Response = Httpclient.getasync (new Uri (URL)).
                result; Write ("Amosli.png", response. Content.readasbytearrayasync ().
                
                result);
        Console.WriteLine ("Enter Picture Verification Code:");        String Imgcode = "Wupve";//The authentication code is written locally and needs to be filled in manually imgcode = Console.ReadLine ();
                Start login URL = "Http://passport.cnblogs.com/login.aspx";
                list<keyvaluepair<string, string>> paramlist = new list<keyvaluepair<string, String>> ();
                Paramlist.add (New keyvaluepair<string, string> ("__eventtarget", ""));
                Paramlist.add (New keyvaluepair<string, string> ("__eventargument", ""));
                Paramlist.add (New keyvaluepair<string, string> ("__viewstate", __viewstate));
                Paramlist.add (New keyvaluepair<string, string> ("__eventvalidation", __eventvalidation));
                Paramlist.add (New keyvaluepair<string, string> ("Tbusername", username));
                Paramlist.add (New keyvaluepair<string, string> ("Tbpassword", password)); Paramlist.add (New keyvaluepair<string, string> ("Lbd_vcid_c_login_logincaptcha", Lbd_vcid_c_login_logincaptcha));
                Paramlist.add (New keyvaluepair<string, string> ("Lbd_backworkaround_c_login_logincaptcha", "1"));
                Paramlist.add (New keyvaluepair<string, string> ("Captchacodetextbox", Imgcode));
                Paramlist.add (New keyvaluepair<string, string> ("Btnlogin", "Login"));
                Paramlist.add (New keyvaluepair<string, string> ("Txtreturnurl", "http://home.cnblogs.com/")); Response = Httpclient.postasync (new Uri (URL), new Formurlencodedcontent (Paramlist)).
                result; result = Response. Content.readasstringasync ().
                result;
            Write ("mycnblogs.html", result); While, result.

            Contains ("Verify code Error, trouble you re-enter"); Console.WriteLine ("Login succeeded.")
            
            ");
        Use up to remember to release httpclient.dispose ();
        public static void Main () {logincnblogs (); }

}

Code Analysis:

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

Second, you use the Get method:

Httpclient.getasync (New  Uri (URL)). result;
 String result = Response. Content.readasstringasync (). result;

Furthermore, the Post method is used:

  list<keyvaluepair<string, string>> paramlist = new list<keyvaluepair<string, String>> ();
                Paramlist.add (New keyvaluepair<string, string> ("__eventtarget", <
Related Article

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.