C#_ Automated Test 1_ simulation post,get_12306 train ticket website automatic login tool

Source: Internet
Author: User
Tags ticket

Remember 2011 years of Spring Festival, 12306 train tickets booking site often crashes cannot log in. Today we will develop a 12306 website automatic login software. Help you book tickets easily

With the first two blog fiddler Tutorials and an explanation of the HTTP protocol, we learned about the principles of the web.

The web principle is that the browser sends a request to the Web server, and the Web server sends an HTTP response to the browser after processing the request.

If we use our own program to send the request to the Web server, and then capture the Web server sent back response. Check that it is consistent with the expected value. Isn't that the Web Automation test?  Such automated tests are called request-response tests, and do not underestimate such automated testing. What Happy Farm Assistant, automatic voting machine. Web crawlers are all made with this.

Read Catalogue

    1. . NET provides a class to send HTTP Request
    2. Usage of the WebClient class
    3. Simulating the "GET" method
    4. Processing of cookies
    5. How to interact with HTTPS Web sites
    6. Simulate the "POST" method
    7. Client sends data to the server for UrlEncode processing
    8. Example: 12306 Train Tickets Website Login tool
    9. Source code Download
. NET provides a class to send HTTP Request

Under the System.Net naming tool,.  NET provides 5 ways to send HTTP request and retrieve HTTP Response. Each of them is

WebClient:

Webrequent-webresponse:

Httpwebrequest-httpwebresponse:

TcpClient:

Socket:

Of these 5 classes, the most suitable is httpwebrequest-httpwebresponse, which can satisfy the function we need. By the way, the use of the WebClient class

Usage of the WebClient class

WebClient is extremely simple to use, mainly for downloading files, or simply getting response. This class does not emulate the "POST" HTTP Request, which has few features.

Examples are as follows:

        void Main (string[] args)         {             // Blog Park home address   "http://www.cnblogs.com";
String html = Sr. ReadToEnd (); Sr. Close (); St. Close ();
Console.Write (HTML); }

Simulating the "GET" method

We mainly use the Httpwebrequest-httpwebresponse two classes to do automated testing.

First look at how to simulate the "GET" method to open the blog home page, in the following example, set some HttpWebRequest some properties

        Staticvoid Main (String[] (args) {//Blog Park Home Address String uri ="Http://www.cnblogs.com";
HttpWebRequest Req = (HttpWebRequest) webrequest.create (URI);//Ways to interact with browsers and serversReq.method ="GET";//Browser type, ie or FirefoxReq.useragent ="mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;)";//Whether to allow automatic redirection (auto-jump)Req.allowautoredirect =True//Number of automatic jumps Req.maximumautomaticredirections = 3; // time-out 50000=50 seconds Req.timeout = 50000; //true;
HttpWebResponse response = (HttpWebResponse) req.getresponse (); Stream stream = Response. GetResponseStream (); Encoding myencoding = encoding.getencoding (utf-8< Span style= "color: #800000;" >"); StreamReader StreamReader = new StreamReader (Stream, myencoding); string html = streamreader.readtoend ();
Console.Write (HTML);}

Processing of cookies

Another important question is, how do we deal with cookies? program and Web server interaction, the program needs to send a cookie to the Web server, the Web server will also send a new cookie to the program. How do we simulate this?

C # provides the Cookiecontainer object.  HttpWebRequest will use the cookie in Cookiecontainer when sending the request.  HttpWebResponse the cookie of the Cookiecontainer object is automatically modified when the response is returned. In that case, cookies don't have to worry about us. Very simple to use

            New Cookiecontainer ();             HttpWebRequest Req = (HttpWebRequest) webrequest.create (URI);             Req.cookiecontainer = Mycookiecontainer;

How to interact with HTTPS Web sites

We use the browser to open the HTTPS website, if we do not install the certificate, usually the page will show "This site's security certificate is a problem", we must click "continue to this site (not recommended)" To view page information. As shown

So our program, how to ignore the HTTPS certificate error?

As long as you add the following code to the program, you can ignore the HTTPS certificate error, so that our program can communicate with the HTTPS site correctly.

                System.Net.ServicePointManager.ServerCertificateValidationCallback + = (SE, cert, chain, sslerror) + =                 {                      true;                 };

Simulate the "POST" method

The difference between post and get is that post sends the data to the Web server in the body. The code is as follows

View Code
        PublicStaticString GetResponse (String URL,String method,String data) {try {HttpWebRequest req = (HttpWebRequest) webrequest.create (URL); req. KeepAlive =True Req. Method = method. ToUpper (); Req. AllowAutoRedirect =True Req. Cookiecontainer = cookiecontainers; Req. ContentType ="application/x-www-form-urlencoded";
Req. useragent = IE7; Req. Accept ="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; Req. Timeout =50000;
if (method. ToUpper () = ="POSTThe && data! =NULL) {ASCIIEncoding encoding =New ASCIIEncoding ();byte[] postbytes = encoding. GetBytes (data);; Req. ContentLength = Postbytes.length; Stream st = Req. GetRequestStream (); St. Write (Postbytes,0, Postbytes.length); St. Close (); }
System.Net.ServicePointManager.ServerCertificateValidationCallback + = (SE, cert, chain, sslerror) + = { return true;};
Encoding myencoding = encoding.getencoding ("UTF-8");
HttpWebResponse res = (HttpWebResponse) req. GetResponse (); Stream resst = Res. GetResponseStream (); StreamReader sr = New StreamReader (RESST, myencoding); string str = Sr. ReadToEnd ();
return str;} catch (Exception) { return string. Empty; } }

Client sends data to the server for UrlEncode processing

It is important to note that the Web client sends data to the Web server if it contains spaces and special characters (for example, Chinese characters) to be urlencode.

It's easy to solve the problem.

Add system.web component in C # Reference

Add the System.Web namespace and then call the Httputility.urlencode () method to encode it

Example: 12306 Train Tickets Website Login tool

In 2011 the Ministry of Railways introduced 12306 train ticket booking sites, but because visitors were too many, they often collapsed. Can't log in at all. Site visit peak time, there is no way to log on success, always error (such as)

Let's use the above knowledge to develop an automatic login tool

First we use the browser to open 12306 Web site to log in, while opening Fiddler to grab Packet analysis, to see how the browser interacts with the Web server.

By grasping packet analysis, we found that login is actually very simple. is to submit the user name, password and verification code to the server via the "POST" method. As shown

In Fiddler We click Inspectors Tab->textview tab to see the data submitted to the Web server is

String Data="loginuser.user_name=thisisusername&nameerrorfocus=&user.password=thispassword& passworderrorfocus=&randcode=cf99&randerrorfocus=";  

We change the username, password, and verification code to a variable and post it to the Web server.

You need to enter a verification code when logging in. Fortunately, the 12306 site here has a bug, when the verification code image is not active refresh, the old verification code can always be used. In this way our tool uses the old verification code to send the login HttpRequest to the server until the login is successful.

The core code of the login is as follows, the actual code is more complex than this, to write a circular call, but also to write a multi-threaded, complete please refer to the source code

The specific code is

String data ="Loginuser.user_name="+ userName + "&nameerrorfocus=&user.password="+ password + "&passworderrorfocus =&randcode="+ code + "&randerrorfocus=focus "; string loginurl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=login"; string afterlogin = Httphelper.getresponse (loginurl, "POST", data);     

Source code Download

Post-run effects are as follows

Complete code Please click this link: 12306 Train ticket reservation website Automatic login tool please open with VS2008

After a while to write a blog, I will introduce the 12306 train ticket automatic booking tool development process.  This tool can automatically log in and order automatically. Buying a train ticket is a small case.

Attached: Automated Test series tutorial, (in serial, please look forward to)

Automated testing (i) 12306 train ticket website automatic login tool

Automated Testing (ii) look at the plug

Automated Testing (iii) Principles of Web Automation testing

Automated Testing (iv) automatic uninstallation of software

Automated Testing (v) Read and write the registry of 64-bit operating systems

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.