12 articles C # network programming-2 Articles HTTP application programming (I)

Source: Internet
Author: User

We are most familiar with network programming than Http. Well, let's start with Http. First of all, we must understand the basic principles and actions of http. The working principles of http are as follows:

A certain degree of understanding will be of great help to us in the following learning.

 

I. Working methods

①: The client and server establish a reliable TCP connection.

②: The client then sends an http request to the server through Socket.

③: The server processes the request and returns the processed data.

④: In http1.0, the tcp connection between the client and the server is immediately disconnected.

However, in http1.1, because "tcp persistent connection" is supported by default, the server uses the Timeout Policy to disconnect the tcp connection.

 

Ii. Features

①: Http is stateless. I believe everyone knows this.

②: The client appends some information to the Header of the Http request to tell the Server about the sent subject, such as the type and encoding of the subject.

 

3. Exploring Http requests and responses

I believe everyone knows that the common request methods are "Get" and "Post". Let's look at the interesting places of Get and Post. Let's talk about it first.

I enter www.baidu.com and will find the following request and response information.

 

1: "Request Header":

Line 1: Get/Http/1.1

There are three pieces of information: ① "Get", indicating the request mode. ② "/", Request the root directory of the website. ③ "Http/1.1", which is the http Version.

Row 2: Host

The website to which the request target is associated with "/" is "www.baidu.com /".

Row 3: Connection

The default value is "keep-Alive". Long connections are supported by default.

Row 4: Cache-Control

This is related to caching. max-age indicates the cache time (s ).

Row 5: User-Agent

Tell serve the identity of my client, which is generally determined by the browser, such as the browser type and version.

Row 6: Accept

And the following Accept headers indicate the types and types that the client can receive.

Last line: Cookie

If the cookie information is not found in the first request to baidu, because the cookie related to baidu cannot be found in the browser,

When we refresh the page for the second time, the get request will find the local cookie and attach it to the server.

 

2: "Response Header ":

Line 1: Http/1.1 200 OK

We all know this. 200 indicates the returned status code, and OK indicates the descriptive status code.

Row 2: Date

Indicates the server response time.

Row 3: Server

The server that responds to the client.

Row 4: Content-Length

The length of the byte stream that the server returns to the client.

Row 5: Content-Type

Indicates the type of the body.

Row 7: Expires

Tell the client the absolute expiration time, such as 2012.1.10. During this time, the client can directly obtain the expiration time from the client cache without sending a request,

It is very beneficial to cache js, css, and image. Therefore, using this attribute is very helpful to our http performance.

Row 8: Content-Encoding

The file type encoding method. The server uses gzip to compress the file. This reduces the size of the file, which is helpful for downloading, but must be supported by the client.

Gzip decoding.

 

The post method is the same. I will not mention it here. The above lists so many methods that we hope you can master the Http details to a certain extent.

 

Iv. application scenarios

Network Programming on http is generally used for two tasks.

①: Crawls data, simulates logon, and automatically fills out a table.

②: Upload and download files.

However,. net encapsulates Http and provides HttpWebRequest and HttpWebResponse to provide common operations. If you have a comparison with Http

Clear understanding I think the attributes and methods in the class library are Shenma and fuyun.

 

V. Case studies

Since it was the first article, we made a simple "brute-force cracking" small program based on the idea of "simulated login", which is very simple.

Step 1: Write two actions, one login and one index ).

 
1 namespace Test. Controllers
2 {
3 [HandleError]
4 public class HomeController: Controller
5 {
6 public ActionResult Login ()
7 {
8 return View ();
9}
10
11 [HttpPost]
12 public ActionResult Index (Model model)
13 {
14 if (model. UserName = "11" & model. Password = "11 ")
15 return View (model );
16 else
17 return RedirectToAction ("Login ");
18}
19
20 public ActionResult About ()
21 {
22 return View ();
23}
24}
25
26 public class Model
27 {
28 public string UserName {get; set ;}
29
30 public string Password {get; set ;}
31}
32}



 

All right, open fiddler, enter admin and admin, and click Submit to see what has been posted to the server, so that we can simulate logon later,

I believe you can understand the head information here.

Step 2: Create a winform program.

 
1 namespace Http
2 {
3 public partial class Form1: Form
4 {
5 public Form1 ()
6 {
7 InitializeComponent ();
8}
9
10 private void Form1_Load (object sender, EventArgs e)
11 {
12 // enter the webbrowser1 control in the webpage content
13 string url = "http: // localhost: 59773 /";
14
15 // create an http Link
16 var request = (HttpWebRequest) WebRequest. Create (url );
17
18 var response = (HttpWebResponse) request. GetResponse ();
19
20 Stream stream = response. GetResponseStream ();
21
22 StreamReader sr = new StreamReader (stream );
23
24 string content = sr. ReadToEnd ();
25
26 webBrowser1.DocumentText = content;
27}
28
29 /// <summary>
30 // brute-force cracking
31 /// </summary>
32 // <param name = "sender"> </param>
33 // <param name = "e"> </param>
34 private void button#click (object sender, EventArgs e)
35 {
36 var url = "http: // localhost: 59773/Home/Index ";
37
38 // The last returned result
39 string prev = string. Empty;
40
41 for (int I = 0; I <100; I ++)
42 {
43 var username = new Random (DateTime. Now. Millisecond). Next (8, 19). ToString ();
44
45 Thread. Sleep (2 );
46
47 var password = new Random (DateTime. Now. Millisecond). Next (8, 19). ToString ();
48
49 // post submitted content
50 var content = "username =" + username + "& password =" + password;
51
52 // convert content into byte format
53 var bytes = Encoding. UTF8.GetBytes (content );
54
55 var request = (HttpWebRequest) WebRequest. Create (url );
56
57 // Based on the submitted information viewed in fiddler, we also try to append such information and then submit
58 request. Method = WebRequestMethods. Http. Post;
59 request. Timeout = 1000*60;
60 request. AllowAutoRedirect = true;
61 request. ContentLength = bytes. Length;
62 request. ContentType = "application/x-www-form-urlencoded ";
63
64
65 // write content into the post request
66 var stream = request. GetRequestStream ();
67 stream. Write (bytes, 0, bytes. Length );
68 stream. Close ();
69
70 // write successful, GET request stream
71 var response = (HttpWebResponse) request. GetResponse ();
72
73 var sr = new StreamReader (response. GetResponseStream ());
74
75 var next = sr. ReadToEnd ();
76
77 if (string. IsNullOrEmpty (prev ))
78 {
79 prev = next;
80}
81 else
82 {
83 if (prev! = Next)
84 {
85 webBrowser2.DocumentText = next;
86 MessageBox. Show ("congratulations, the password has been cracked! Total cost: "+ (I + 1) +" Times, username: "+ username +", password: "+ password );
87 return;
88}
89}
90
91}
92 webBrowser2.DocumentText = "sorry, failed to crack ";
93}
94}
95}


Www.2cto.com

 

Step 3: click "brute force cracking" to see if you can enumerate the username and password of the "zombie Website" for me.

 

Haha, the reality is far more simple than that, mainly to let everyone have an understanding of HttpWebReqeust and HttpWebResponse


Author's first-line codenon

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.