Android Network Programming (I) HTTP protocol Principle

Source: Internet
Author: User

Android Network Programming (I) HTTP protocol Principle
Preface

This article is the beginning of this series. As a mobile developer, the developed applications will inevitably access the network. Although there are already many open source libraries to help us easily access the network, however, we still need to understand the principle of network access, which is also a required knowledge point for excellent developers. In this article, we will first look at the principles of the HTTP protocol.

1. HTTP Overview

HTTP is an object-oriented protocol at the application layer. It is applicable to distributed hypermedia information systems due to its simple and fast method. It proposed in 1990 that, after several years of use and development, it has been continuously improved and expanded.

Main features of HTTPSupports the C/S (customer/Server) mode. Simple and fast: when a customer requests a service from the server, only the Request Method and path are required. Common Request methods include GET, HEAD, and POST. Each method specifies the type of contact between the customer and the server. Because the HTTP protocol is simple, the program size of the HTTP server is small, so the communication speed is fast. Flexible: HTTP allows transmission of any type of data objects. The Type being transferred is marked by Content-Type. No connection: No connection means that only one request is allowed for each connection. After the server processes the customer's request and receives the customer's response, the connection is disconnected. This method can save transmission time. Stateless: HTTP is a stateless protocol. Stateless means that the Protocol has no memory for transaction processing. The lack of status means that if subsequent processing requires the previous information, it must be re-transmitted, which may increase the amount of data transmitted each connection. On the other hand, when the server does not need previous information, its response is faster. The http url format is as follows:
http://host[":"port][abs_path]

Http indicates that network resources are to be located through the HTTP protocol; host indicates a valid Internet host domain name or IP address; port specifies a port number. If it is null, the default port 80 is used; abs_path specifies the URI of the requested resource (any available resources on the Web ).
HTTP has two types of packets: Request Message and Response Message. Let's take a look at the request message.

2. HTTP request packets

Let's take a look at the general format of the Request Message:

Generally, an HTTP request is composed of four parts: request line, request header, blank line, and request data.

Request Line

The request line consists of the Request Method, URL field, and HTTP version. The format is as follows:

Method Request-URI HTTP-Version CRLF

The Method indicates the Request Method, the Request-URI is a unified resource identifier, the HTTP-Version indicates the HTTP protocol Version of the Request, and the CRLF indicates the carriage return and line feed (except for the CRLF as the end, separate CR or LF characters are not allowed ).

There are eight HTTP request methods: GET, POST, DELETE, PUT, HEAD, TRACE, CONNECT, and OPTIONS. PUT, DELETE, POST, and GET correspond to addition, deletion, modification, and query respectively. For mobile development, POST and GET are the most commonly used.

GET: Request to GET the resource POST identified by Request-URI: after the resource identified by Request-URI is appended with a new data HEAD Request to obtain the Response Message Header of the resource identified by Request-URI, The PUT Request server stores a resource, use Request-URI as its identifier. The DELETE Request server deletes the resource TRACE information identified by Request-URI, it is mainly used to test or diagnose whether CONNECT retains the performance of the server to be queried using OPTIONS requests in the future, or to query resource-related OPTIONS and requirements.

For example, the request line for accessing my CSDN blog address is:

GET http://blog.csdn.net/itachi85 HTTP/1.1
Request Header

There are 0 or more request headers after the request line. Each request header contains a name and a value, which are separated. The request header will send a carriage return and line feed with an empty line, notifying the server that there will be no request headers below. The request header will be explained in the next section of the message header.

Request data

The request data is not used in the GET method, but in the POST method. The POST method is applicable when a user needs to fill out a form. The most common request headers related to request data are Content-Type and Content-Length.

3. HTTP response packets

Let's take a look at the general format of the Response Message:

The HTTP Response Message consists of the Status line, message header, blank line, and response body. As described later in the response header, the response body is the content of the resource returned by the server. Let's take a look at the status line.

Status line

1. The status line format is as follows:

HTTP-Version Status-Code Reason-Phrase CRLF

HTTP-Version indicates the HTTP protocol Version of the server, Status-Code indicates the response Status Code sent back by the server, and Reason-Phrase indicates the text description of the Status Code.
The status code consists of three numbers. The first number defines the response category and has five possible values:

100 ~ 199: indicates that the request has been received and the request continues to be processed ~ 299: the request is successful, indicating that the request has been successfully received, understood, and accepted. 300 ~ 399: redirection. Further operations must be performed to complete the request. 400 ~ 499: client error. The request has a syntax error or the request cannot be implemented 500 ~ 599: the server fails to fulfill valid requests due to a server error.

Common status codes are as follows:

200 OK: client Request successful 400 Bad Request: the client Request has a syntax error and cannot be understood by the server. 401 Unauthorized: the Request is Unauthorized, this status code must be used with the WWW-Authenticate header domain 403 Forbidden: the Server receives the request, but rejects the service 500 Internal Server Error: the Server has an unexpected Error 503 Server Unavailable: the server cannot process client requests currently, and may return to normal after a period of time

For example, the status line for accessing the response of my CSDN blog address is:

HTTP/1.1 200 OK
4. HTTP message header

The message headers are classified into common headers, request headers, response headers, and object headers. A message header is composed of key-value pairs. Each line has one pair. The keywords and values are separated by the colon.

General Header

Either in the request header or in the Response Header

Date: indicates the Date and time of message generation. Connection: Allows sending the specified Connection. For example, if the specified Connection is continuous or the "close" option is specified, the Notification Server is notified. After the response is complete, disable connection Cache-Control: used to specify Cache commands. Cache commands are unidirectional (Cache commands in the response may not appear in the request ), independent (the cache command of one message does not affect the cache mechanism of the other message processing) Request Header

The request header notifies the server of the client request information. Typical request headers include:

Host: The Host Name of the request. Multiple Domain Names are allowed to have one IP address at the same time, that is, the virtual Host User-Agent: the browser type of the request sent, the operating system, and other information Accept: the list of content types that can be recognized by the client. It is used to specify the types of information that the client receives. Accept-Encoding: The data Encoding that the client can recognize. Accept-Language: indicates the Language type supported by the browser. Connection: allow the client and server to specify options related to the request/response connection. For example, if this is Keep-Alive, the connection is maintained. Transfer-Encoding: indicates the receiver's Encoding method to ensure reliable transmission of packets. Response Header

It is used for the response of the server to transmit its own information. Common Response Headers:

Location: Used to redirect the receiver to a new Location. When the domain name is changed, the Server contains the system information that can be used by the Server to process the request, which corresponds to the User-Agent request header. Object Header

The object header is used to specify the information of the transferred resource. It can be used for both requests and responses. Both request and response messages can send an object. Common Object headers are:

Content-Type: the media Type of the Object Body sent to the recipient. Content-Lenght: the length of the Object Body. Content-Language: the natural Language used to describe the resource, if this option is not set, the object Content will be provided to all languages for reading Content-Encoding: the object header is used as a modifier of the media type, the value indicates the encoding of the additional Content that has been applied to the object body. To obtain the media Type referenced in the Content-Type header field, the corresponding decoding mechanism must be used. Last-Modified: the object header is used to indicate the Last modification date and time of the resource. Expires: the object header provides the response expiration date and time. 5. Application Example

To view the request message and Response Message of a webpage or mobile phone request network, we recommend using Fiddler here, android uses Fiddler to capture network data packets. This article details how to use Fiddler.
Open Fiddler and access my CSDN blog website in a browser:

Click the red brush area to view the request message and Response Message.

Request Message:

GET http://blog.csdn.net/itachi85 HTTP/1.1 // request line Host: blog.csdn.net // Request Header Connection: keep-aliveCache-Control: max-age = 0 Accept: text/html, application/xhtml + xml, application/xml; q = 0.9, image/webp, */*; q = 0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36 QQBrowser/9.3.6872.400Accept-Encoding: gzip, deflate, sdchAccept-Language: zh-CN, zh; q = 0.8 Cookie: bd1__firstime = 1443768140949; uid_tt_dd = 50285292501_960147_20151002 ;... omitted

The request method is GET, because the GET method does not request data.

Response Message:

HTTP/1.1 200 OK // status line Server: openresty // Response Header Date: Sun, 27 Mar 2016 08:26:54 GMTContent-Type: text/html; charset = utf-8Transfer-Encoding: chunkedConnection: keep-aliveKeep-Alive: timeout = 20 Vary: Accept-EncodingCache-Control: privateX-Powered-By: PHP 5.4.28Content-Encoding: gzip // spaces that cannot be omitted 28b5} ysI 1? Fsgl n-] {^ _ {'z! C, m #0! L '4x ly .? *? ZAt_Xl * 9 'O? '? 3 ^ 1a... omitted

There is nothing to say about the response message. Next we configure the mobile network proxy to access an application interface.

Request Message:

POST http://patientapi.shoujikanbing.com/api/common/getVersion HTTP/1.1 // request line Content-Length: 226 // Request Header Content-Type: application/x-www-form-urlencodedHost: patientapi. shoujikanbing. comConnection: Keep-AliveUser-Agent: Mozilla/5.0 (Linux; U; Android 4.4.4; zh-cn; mi note lte Build/KTU84P) AppleWebKit/533.1 (KHTML, like Gecko) version/4.0 Mobile Safari/533.1Accept-Encoding: gzip // spaces that cannot be omitted, the following is the request data clientversion = 2_2.0.0 & time = 1459069342 & appId = android & channel = hjwang & sessionId = token & token = token & deviceId = 869436020220717 & type = 2 & version = 2.0.0

From the request line of the request message, the request method is POST, and the request address is callback.

Response Message:

HTTP/1.1 200 OK // status line Server: nginx // Response Header Date: Sun, 27 Mar 2016 09:02:20 GMTContent-Type: text/html; charset = utf-8Transfer-Encoding: chunkedConnection: keep-aliveVary: Accept-EncodingSet-Cookie: sessionId = enabled; expires = Mon, 28-Mar-2016 09:02:20 GMT; Max-Age = 86400; path =/; domain =. shoujikanbing. comSet-Cookie: PHPSESSID = 0d1cee1f31926ffa8894c6 4804efa855101d56eb21caf5db5dcb9a4955b7fbc9; path =/; domain =. shoujikanbing. comExpires: Thu, 19 Nov 1981 08:52:00 GMTCache-Control: no-store, no-cache, must-revalidate, post-check = 0, pre-check = 0 Pragma: no-cacheContent-Encoding: gzip // space that cannot be omitted 17f // The Encoding format of the entity message is gzip. Therefore, the response data shown here is garbled mP N @ "E? N m 1 w (HL (1 ^ P nK E? 93 '3gnlh 7 P $ c \ T 4a6 L: + 1dY % $ g h +... omitted

The entity of the Response Message uses the encoding format gzip, so garbled characters are displayed in the Fiddler software.

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.