Web security practice (4) c # simple http programming example

Source: Internet
Author: User

Web security practice (4) c # simple http programming example
For http programming, we can follow the http protocol in Socket mode. For http programming, Microsoft provides encapsulated classes such as WebRequest, WebResponse, HttpWebRequest, and HttpWebResponse, for more information about these classes, see other articles in the blog. I will only briefly introduce the HttpWebRequest and HttpWebResponse classes I use. It may take some time to build a good http program. I am not here to provide a molding tool. It is just a simple example. The time is limited. I hope you will forgive me.
HttpWebRequest class
The HttpWebRequest class supports the attributes and methods defined in WebRequest and the additional attributes and methods that allow users to directly interact with servers using HTTP.
Do not use HttpWebRequest constructor. Use the WebRequest. Create method to initialize a new instance of HttpWebRequest. If the URI scheme is http: // or https: //, Create returns the HttpWebRequest instance.
The GetResponse method sends a synchronous request to the Internet resource specified in the RequestUri attribute and returns an HttpWebResponse instance containing the response. You can use the BeginGetResponse and EndGetResponse methods to send asynchronous requests to Internet resources.
When you want to send data to Internet resources, the GetRequestStream method returns the Stream instance used to send data. The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the sent data stream.
The following example creates an HttpWebRequest for URI http://www.bkjia.com.

HttpWebRequest myReq = (HttpWebRequest) WebRequest. Create ("http://www.bkjia.com /");


HttpWebResponse class
This class includes support for HTTP-specific usage of attributes and methods in the WebResponse class. The HttpWebResponse class is used to generate an HTTP independent client application that sends HTTP requests and receives HTTP responses.
Note: Do not confuse HttpWebResponse and HttpResponse; the latter is used for ASP. NET applications, and its methods and attributes are made public through the internal HttpResponse object of ASP. NET.
You must never directly create an instance of the HttpWebResponse class. Instead, use the instance returned by calling HttpWebRequest. GetResponse.
Call the GetResponseStream method to return the response content from Internet resources in the form of Stream.
The following example returns HttpWebResponse of HttpWebRequest:
HttpWebRequest HttpWReq = (HttpWebRequest) WebRequest. Create ("http://www.bkjia.com ");
HttpWebResponse HttpWResp = (HttpWebResponse) HttpWReq. GetResponse ();

// Insert code that uses the response object.
HttpWResp. Close ()


Uri class
URI is a concise representation of resources that can be used by applications on the Internet. The Uri class defines attributes and methods to process Uris, including analysis, comparison, and combination. The Uri class attribute is read-only, and the UriBuilder class must be used to modify the Uri instance.
The Uri class only stores absolute Uris (for example, "http://www.bkjia.com/index.htm "). Relative URI (for example, "/new/index.htm") must be expanded relative to the base URI, which is absolute. Provides the MakeRelative method to convert an absolute URI to a relative URI when necessary.
Uris are stored as normalized Uris by escape codes. All characters with ASCII values greater than 127 are replaced with their equivalent hexadecimal numbers. To normalize the URI format, perform the following steps.
Convert the URI scheme to lowercase. Convert the host name to lowercase. Remove the default and empty port numbers. Remove unnecessary segments (such as "/" and "/test") to simplify the URI.

Using the ToString method, you can convert the content of the Uri class from the URI reference of the escape code to a readable URI reference.

Some Uris include segment identifiers or queries. The segment identifier is any text in the URI following the digit sign (#) and is stored in the Fragment attribute. The query information is followed by the question mark (?) in the URI (?) Any text after the Query is stored in the Query attribute.

Note: The URI class supports IP addresses in the following format: IPv4 protocol in four groups of notation and hexadecimal IPv6 protocol separated by colons. Remember to enclose the brackets on both sides of the IPv6 address, such as http: // [: 1].

 

The following example creates an instance of the Uri class and uses it to create a WebRequest.

Uri siteUri = new Uri ("http://www.bkjia.com /");

WebRequest wr = WebRequest. Create (siteUri );

 

Program example

In the interface design, a textbox Control is used to enter the address. The three combobox controls provide the selection of the request and encoding modes and the number of consecutive sending times, because different servers may support different request methods, different pages may also be encoded in different ways.

The other two textbox controls are used to display the header information and content information respectively.

(1) Information Processing class ProcessInfo. We pass various parameters input by the user to this class, which is responsible for sending requests and receiving responses. The main functions provided below are described in conjunction with the code.

/// <Summary> /// send a request to receive a response /// </summary> /// <param name = "tb"> TextBox showing the header information </param> /// <param name = "ta"> TextBox for displaying content </param> /// <param name = "method"> Request method </param> /// <param name = "codemethod"> encoding method </param> public void SendInfo (TextBox tb, textBox ta, string method, string codemethod) {// first, we create an instance of HttpWebRequest to send the request. Hwr = (HttpWebRequest) WebRequest. Create (uri); // set the request method. Hwr. method = method; CodingMethod = codemethod; try {// create an HttpWebResponse instance response = (HttpWebResponse) hwr. getResponse (); // because of response. headers contains the desired header information, which is of the WebHeaderCollection type // so we create the WebHeaderCollection instance myheaders and convert it to a string. WebHeaderCollection myheaders = response. Headers; f1.AddInfo (myheaders. ToString (), ta); // GetResponseStream () method. The obtained information is the returned content. Stream resStream = response. getResponseStream (); int count = resStream. read (buf, 0, buf. length); f1.AddInfo (getString (buf), tb); hwr. abort (); resStream. close (); response. close ();} catch (Exception e) {MessageBox. show (e. toString ();} finally {Thread. currentThread. abort ();}}

(2) Main Functions of form1.

This is the event processing function by clicking the button to obtain various parameters set by the user, and then start a separate thread to call methods related to the information processing class ProcessInfo.

Private void button_send_Click (object sender, EventArgs e) {// some code is omitted for (int I = 0; I <Int32.Parse (this. comboBox_sendtiems.SelectedItem.ToString (); I ++) {Thread t = new Thread (new ThreadStart (GetInfo); t. start () ;}/// <summary> // pass the parameter to the processing function of the ProcessInfo class /// </summary> private void GetInfo () {ProcessInfo pi = new ProcessInfo (textBox_uri.Text, this); pi. sendInfo (textBox_content, textBox_head, combox1, combox2 );} /// <summary> /// used for asynchronous calling to add response information to textbox /// </summary> /// <param name = "info"> </param> /// <param name = "myt"> </param> public void AddInfo (string info, textBox myt) {// determine whether it is a cross-thread call if (myt. invokeRequired) {SetInfoCallback sic = new SetInfoCallback (AddInfo); this. invoke (sic, new object [] {info, myt});} else {myt. text + = info ;}}

Well, this simple example may not give you too much inspiration, but I still have to move forward in this series. For more programming practices, if you have done so, you must share it. Isn't it fun to be alone!

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.