Visual C # HTTP protocol development

Source: Internet
Author: User
Visual C # HTTP protocol development
  1. HTTP protocol Overview

    1. HTTP protocol Overview
    2. HTTP Request
    3. HTTP Response
  2. Introduction to HTTP-related classes
    1. Webrequest class
    2. Webresponse class
    3. Httpwebrequest class
    4. Httpwebresponse class
    5. Uri class
HTTP Overview

In the TCP/IP architecture, HTTP belongs to the application layer protocol and is located at the top layer of the TCP/IP protocol. When browsing the Web, the browser exchanges information with the Web server over HTTP. The format of this information (document) type is defined by mime.

HTTP has the following features:

  1. HTTP works in customer/Server mode
    HTTP supports communication between the client (usually a browser) and the server to transmit data to each other.
    The reasons for the http-defined Service are as follows:

    • Establish a connection between the customer and the server;
    • The customer makes a request to the server;
    • If the request is accepted, the server returns the response, including the status code and required files;
    • Disconnect the customer from the server
    An HTTP operation is called a transaction ).
  2. HTTP is stateless
    That is to say, the browser and the server establish a connection every time they perform an HTTP operation, but the connection is interrupted when the task ends.
  3. HTTP uses metadata as the header
    HTTP adds a header to all transactions ). That is to say, adding a piece of information before the main data is called metainformation ). It enables the server to provide information about the data being transferred. For example, the type and language of the object to be transferred.
    In terms of functions, HTTP supports four types of metadata: General information header, request header, response header, and entity header.
  4. HTTP supports two request and response formats
    HTTP consists of two parts: one is the request sent from the browser to the server, and the other is the response of the server to the customer.
    HTTP supports two types of requests and responses: simple requests, full requests, simple responses, and full responses.
  5. HTTP is a simple text-based protocol.
HTTP Request

Common HTTP request methods:

Method Description
Get Request to read a web page
Head Request to read the header of a web page
Put Request to store a web page
Post Attaching to a named Resource
Delete Delete Web Page
Link Connect two existing resources
Unlink Cancel an existing connection between two resources

The HTTP request format is as follows:

<Request-line>
<Headers>
<Blank line>
[<Request-body>]

In an HTTP request, the first line must be a request line to describe the request type, resources to be accessed, and the HTTP Version Used. Next is a header section, which describes additional information to be used by the server. After the header is a blank line, you can add any other data [called the body].
HTTP defines a large number of request types, but Ajax developers only care about GET requests and post requests. As long as you enter a URL in the web browser, the browser will send a GET request to the server based on the URL to tell the server what resources are obtained and returned. The GET request for www.wzu.edu.cn is as follows:

Get, HTTP, 1.1
HOST: www.wzu.edu.cn
User-Agent: Mozilla/5.0 (windows; U; Windows NT 5.1; en-us;
RV: 1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: keep-alive

The first part of the request line indicates that the request is a GET request. The second part of the row is a slash (/), which indicates that the request is the root directory of the domain name. The last part of this row indicates that HTTP 1.1 is used (another option is 1.0 ). So where can I send the request? This is the content of the second line.
Row 2nd is the first request header, host. The first host indicates the request destination. Combined with the forward slash (/) in the previous line, you can notify the server that the request is www.wzu.edu.cn/(HTTP 1.1 requires the first host, but the original version 1.0 does not need to be used ). The third line contains the first User-Agent, which can be accessed by both the server and client scripts. It is an important basis for browser type detection logic. This information is defined by your browser (Firefox 1.0.1 in this example) and will be automatically sent in each request. The last line is the first connection. Usually, the browser operation is set to keep-alive (of course other values can be set, but this is beyond the scope discussed in this book ). Note that there is a blank line after the last header. This empty line is required even if the request body does not exist.

If you want to obtain a page in the www.wzu.edu.cn/booksdomain such as http://www.wzu.edu.cn, the request can be used in the following way:

GET/books/
HTTP/1.1
HOST: www.wzu.edu.cn
User-Agent: Mozilla/5.0 (windows; U; Windows NT 5.1; en-us;
RV: 1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: keep-alive

Note that only the content of the first line has changed. It only contains the part after www.wzu.edu.cn in the URL.

To send the GET request parameters, these additional information must be appended to the URL itself. The format is similar:

URL? Name1 = value1 & name2 = value2 &... & Namen = valuen

This information is called a query string. It will be copied in the request line of the HTTP request, as shown below:

GET/books /? Name = Professional % 20 Ajax
HTTP/1.1
HOST: www.wzu.edu.cn
User-Agent: Mozilla/5.0 (windows; U; Windows NT 5.1; en-us;
RV: 1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: keep-alive

On the other hand, the POST request provides additional information for the server in the Request body. Generally, when you fill in an online form and submit it, the entered data will be sent to the server as a POST request.

The following is a typical POST request:

Post, HTTP, 1.1
HOST: www.wzu.edu.cn
User-Agent: Mozilla/5.0 (windows; U; Windows NT 5.1; en-us;
RV: 1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: Application/X-WWW-form-urlencoded
Content-Length: 40
Connection: keep-alive
Name = Professional % 20 Ajax & publisher = Wiley

We can see from the above that there are some differences between post requests and GET requests. First, the get at the beginning of the request line is changed to post to indicate different request types. You will find that the header host and User-Agent still exist, and there are two new lines behind it. The Content-Type Header describes how the content of the request body is encoded. The browser always transmits data in the format of application/X-WWW-form-urlencoded, which is a MIME type for simple URL encoding. The Content-Length header specifies the number of bytes of the Request body. A blank line is followed by the request body after the first connection. Like most browser POST requests, this is given in the form of a simple "name-value" pair, where name is professional
Ajax and publisher is Wiley. You can organize URL query string parameters in the same format.

As mentioned above, there are other HTTP request types that follow the same basic format as get and post requests. Next, let's see what response the server will send to the HTTP request.

HTTP Response

As shown below, the HTTP Response format is very similar to the request format:

<Status-line>
<Headers>
<Blank line>
[<Response-body>]

As you can see, the only real difference in response is that the request information is replaced by the status information in the first line. Status line describes the requested resources by providing a status code. The following is an example of an HTTP response:

HTTP/1.1 200
OK
Date: sat, 31 Dec 2005 23:59:59 GMT
Content-Type: text/html; charset = ISO-8859-1
Content-Length: 122

<HTML>
<Head>
<Title> wrox homepage </title>
</Head>
<Body>
<! -- Body goes here -->
</Body>
</Html>

 

In this example, the HTTP status code in the status line is 200 and the message is OK. Status lines always contain status codes and short messages to avoid confusion. The most common status codes are:

  • 200 (OK): The resource is found and everything is normal.
  • 304 (not modified): The resource has not been modified since the last request. This is usually used for browser caching.
  • 401 (unauthorized): the client has no permission to access this resource. This usually requires the user to enter the user name and password in the browser to log on to the server.
  • 403 (Forbidden): the client is not authorized. This is usually because an incorrect user name or password is entered after 401.
  • 404 (not found): the requested resource does not exist at the specified position.

It is the first line after the status line. Generally, the server returns a header named date to indicate the date and time of the response generation (the server usually returns some information about itself, although not required ). You should be familiar with the next two headers, that is, the Content-Type and Content-Length in the post request. In this example, the header Content-Type specifies the MIME type HTML (text/html) whose encoding type is ISO-8859-1 (which is the encoding standard for American English resources ). The response body contains the HTML source file of the requested resource (although it may contain plain text or binary data of other resource types ). The browser displays the data to the user.
Note: The request type for the response is not specified here, but this is not important to the server. The client knows what type of data will be returned for each type of request and determines how to use the data.

Introduction to HTTP-related classes webrequest classes

WebrequestIs the abstract base class of the. NET Framework request/response model used to access Internet data. Applications that use this request/response model can request data from the Internet in an unknown way. In this way, the application processesWebrequestClass, and the specific sub-class of the Protocol executes the specific details of the request.

Requests are sent from an application to a specific URI, such as a web page on the server. Uri fromWebrequestDetermine the appropriate subclass to be created in the Child list. RegisterWebrequestA child is usually used to process a specific protocol (such as HTTP or FTP), but it can also be registered to process requests to paths on a specific server or server.

BecauseWebrequestClass is an abstract class, soWebrequestThe actual behavior of the instance during running is determined by the subclass returned by the webrequest. Create method.

Note:UseCreateMethod to initialize a newWebrequestInstance. Do not useWebrequestConstructor.

The following example shows how to createWebrequestInstance and return a response.

// Initialize
The webrequest.
Webrequest myrequest = webrequest. Create ("http://www.contoso.com ");
// Return
The response.
Webresponse myresponse = myrequest. getresponse ();
// Code
To use the webresponse goes here.
// Close
The response to free resources.
Myresponse. Close (); webresponse class

WebresponseClass is abstract (in Visual BasicMustinheritIs derived from the abstract base class. Applications can useWebresponseThe instance of the class participates in the request and response transactions in an unknown way.WebresponseThe derived protocol-specific class carries the request details.

Client applications are not directly createdWebresponseObject, but by calling the getresponse method on the webrequest instance to create it.

The following example creates a webresponse instance from webrequest.

// Initialize
The webrequest.
Webrequest myrequest = webrequest. Create ("http://www.contoso.com ");
// Return
The response.
Webresponse myresponse = myrequest. getresponse ();
// Code
To use the webresponse goes here.
// Close
The response to free resources.
Myresponse. Close (); httpwebrequest class

HttpwebrequestProvides support for attributes and methods defined in webrequest and additional attributes and methods that allow users to directly interact with servers using HTTP.

Do not use httpwebrequest constructor. UseWebrequest. CreateMethod InitializationHttpwebrequest. If the URI scheme ishttp://Orhttps://, ThenCreateReturnsHttpwebrequestInstance.

GetresponseMethod directionRequesturiThe Internet resource specified in the property sends a synchronous request and returns the httpwebresponse instance containing the response. AvailableBegingetresponseAndEndgetresponseMethod pair
Internet resources send asynchronous requests.

When you want to send data to Internet resources,GetrequeststreamMethod returns the stream instance used to send data.BegingetrequeststreamAndEndgetrequeststreamMethod To provide asynchronous access to the sent data stream.

The following example creates a URI http://www.contoso.com/Httpwebrequest.

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
Httpwebresponse class

This class includes support for HTTP-specific usage of attributes and methods in the webresponse class.HttpwebresponseClass is used to generate an HTTP independent client application that sends HTTP requests and receives HTTP responses.

Note:Do not confuseHttpwebresponseAndHttpresponseThe latter is used
ASP. NET application, and its methods and attributes are passed through the internal ASP. NETHttpresponseObject exposed.

Never directly createHttpwebresponseClass. Instead, useHttpwebrequest. getresponseThe returned instance.

Public header information returned from Internet resources is exposed as a property of this class. For a complete list, see the following table. Other headers can be read as name/value pairs from the headers attribute.

The following table showsHttpwebresponseThe public HTTP header used by class attributes.

Header Attribute
Content-Encoding Contentencoding
Content-Length Contentlength
Content-Type Contenttype
Last-modified Lastmodified
Server Server

By callingGetresponsestreamMethodStreamReturns the response content from Internet resources.

The following example returnsHttpwebresponse:

HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.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.UriClass defines attributes and methods to process Uris, including analysis, comparison, and combination.UriClass attributes are read-only and modifiedUriInstance needs to useUribuilderClass.

UriClass only stores absolute Uris (for example, "http://www.contoso.com/index.htm "). Relative uri (for example, "/New/index.htm") must be expanded relative to the base URI. This is absolute. ProvidedMakerelativeMethod 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 make the URI have a canonicalized format,UriPerform the following steps for the constructor.

  • 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.

UseTostringMethod, you can setUriClass content is converted 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, stored inQueryAttribute.

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 createsUriClass, and use it to create webrequest.

Uri siteuri = new uri ("http://www.contoso.com /");
Webrequest wR = webrequest. Create (siteuri );

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.