Android Network Programming (i) HTTP protocol principle

Source: Internet
Author: User

Preface

This article is the beginning of this series, as a mobile developer, the development of the application will inevitably have access to the network, although now there are many open source libraries to help us to easily access the network, but we still have to understand the principle of network access, this is a good developer of the necessary knowledge points. In this article, let's start by understanding the HTTP protocol principle.

1.HTTP Introduction

HTTP is an object-oriented protocol belonging to the application layer, which is suitable for distributed hypermedia information System because of its simple and fast way. It was proposed in 1990, after several years of use and development, has been continuously improved and expanded.

key features of the HTTP protocol
    1. Support C/S (client/server) mode.
    2. Simple and fast: When a customer requests a service from the server, it simply transmits the request method and path. The request method commonly has, POST, each method specifies that the customer and the server contact type is different. Because the HTTP protocol is simple, the HTTP server's program size is small, so the communication speed is fast.
    3. Flexible: HTTP allows the transfer of any type of data object. The type being transmitted is marked by Content-type.
    4. No connection: The meaning of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives the customer's answer, the connection is disconnected. In this way, the transmission time can be saved.
    5. Stateless: The HTTP protocol is a stateless protocol, and stateless means that the protocol has no memory capacity for transactional processing. A lack of state means that if the previous information is required for subsequent processing, it must be re-routed, which may cause the amount of data to be transferred per connection to increase. On the other hand, it responds faster when the server does not need the previous information.
the format of the HTTP URL is as follows
http://host[":"port][abs_path]

HTTP means to locate network resources through the HTTP protocol; Host represents a legitimate Internet host domain name or IP address; port specifies a port number, or null uses the default port 80;abs_path to specify the URI of the requested resource (any available resource on the Web).
HTTP has two kinds of messages are request messages and response messages, let us first look at the request message.

2.HTTP Request Message

First look at the general format of the request message:

Typically, an HTTP request message consists of a request line, a request header, a blank line, and 4 parts of the request data.

Request Line

The request line consists of the request method, the URL field, and the version of the HTTP protocol, in the following format:

Method Request-URI HTTP-Version CRLF

Where method means the request, Request-uri is a Uniform Resource identifier, http-version represents the HTTP protocol version of the request, CRLF indicates carriage return and newline (except for the CRLF at the end, a separate CR or LF character is not allowed).

There are 8 HTTP request methods, namely get, POST, DELETE, PUT, HEAD, TRACE, CONNECT, OPTIONS. The put, DELETE, post, get respectively corresponding to the increase and deletion, the most common for mobile development is POST and get.

    1. Get: Request for the resource identified by Request-uri
    2. Post: Append new data to the resource identified by Request-uri
    3. HEAD request Gets the response message header for the resource identified by Request-uri
    4. PUT Request server stores a resource and uses Request-uri as its identity
    5. Delete Request server deletes the resource identified by the Request-uri
    6. TRACE requests the server to echo received request information, primarily for testing or diagnostics
    7. CONNECT reserved for future use
    8. Options request the performance of the query server, or query for resource-related choices and requirements

For example I go to visit my CSDN blog address request line is:

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

After the request line there will be 0 or more request headers, each of which contains a name and a value, separated by ":". The request header will send a carriage return and line break with a blank line, notifying the server that there will be no request headers. For the request header, a uniform explanation is made in the following section of the message header.

Request Data

The request data is not used in the Get method, but is used in the Post method. The Post method is useful for situations where customers need to fill out a form, and the most common request headers associated with requesting data are Content-type and content-length.

3.HTTP Response Message

Let's take a look at the general format of the response message:

HTTP response messages consist of a status line, a message header, a blank line, and a response body. After the response header, the response body is the contents of the resource returned by the server, first look at the status line.

Status Line

1, the status line format is as follows:

HTTP-Version Status-Code Reason-Phrase CRLF

Where http-version represents the version of the server HTTP protocol, Status-code represents the response status code sent back by the server, and Reason-phrase represents a textual description of the status code.
The status code consists of three digits, the first number defines the category of the response, and there are five possible values:

    • 100~199: Indicates that the request has been received and continues processing
    • 200~299: The request was successful, indicating that the request was successfully received, understood, accepted
    • 300~399: Redirect to complete the request must be further done
    • 400~499: Client error, request syntax error or request not implemented
    • 500~599: Server-side error, server failed to implement legitimate request

The common status codes are as follows:

    • OK: Client Request succeeded
    • Bad Request: Client requests have syntax errors and cannot be understood by the server
    • 401 Unauthorized: Request unauthorized, this status code must be used with the Www-authenticate header field
    • 403 Forbidden: The server receives the request but refuses to provide the service
    • Internal Server error: Unexpected errors occurred on the server
    • 503 Server Unavailable: The server is currently unable to process client requests and may return to normal after some time

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

HTTP/1.1 200 OK
message header of 4.HTTP

Message headers are divided into common headers, request headers, response headers, entity headers, and so on. The message header consists of key-value pairs, one pair per line, and the keywords and values separated by the English colon ":".

Generic Header

Can appear either in the request header or in the response header

    • Date: Indicates the day and time the message was generated
    • Connection: Allows the option to send a specified connection, such as specifying that the connection is contiguous, or specifying a "close" option to notify the server to close the connection after the response is complete
    • Cache-control: Used to specify the cache instruction, the cache instruction is unidirectional (the cache instruction appearing in the response may not appear in the request), and is independent (the cache instruction of one message does not affect the caching mechanism of another message processing)
Request Header

The request header notifies the server about client-side requests, and the typical request headers are:

    • Host: The requested hostname, which allows multiple domain names to be in the same IP address as the virtual host
    • User-agent: Send requested browser type, operating system and other information
    • Accept: A list of content types that clients can recognize to specify which types of information the client receives
    • Accept-encoding: Client-identifiable data encoding
    • Accept-language: Indicates the type of language supported by the browser
    • Connection: Allows the client and server to specify options related to the request/response connection, for example, this is for keep-alive, which means to keep the connection.
    • Transfer-encoding: Inform the receiving side in order to ensure the reliable transmission of the message, the message adopted what encoding method.
Response Header

A response that is used by the server to pass its own information, a common response header:

    • Location: Used to redirect the recipient to a new position, often when changing the domain name
    • Server: Contains system information that can be used by the server to process the request, as opposed to the User-agent request header
Entity Header

The entity header is used to set the information for the transmitted resource, either for the request or for the response. Both request and response messages can be routed to an entity, and the common entity header is:

    • Content-type: The media type that is sent to the recipient's entity body
    • Content-lenght: Length of entity body
    • Content-language: The natural language used to describe the resource, which is not set, the option is that the entity content will be available to all languages read
    • Content-encoding: The entity header is used as the modifier for the media type, and its value indicates the encoding of the additional content that has been applied to the entity body, so the corresponding decoding mechanism must be used to obtain the media type referenced in the Content-type header domain.
    • Last-modified: The entity header is used to indicate the last modification date and time of the resource
    • Expires: The entity header gives the date and time the response expires
5. Application Examples

In order to view the Web page or mobile request network request message and response message There are many ways, it is recommended to use Fiddler, in the Android use Fiddler network data capture This article detailed how to use the Fiddler, here do not repeat.
Open fiddler and then use your browser to access my CSDN blog site:

Click on the area of the red brush to see the request and response messages.

Request message:

GET Http://blog. Csdn. NET/itachi85 http/1.1Request LineHost:Blog. Csdn. NETRequest HeaderConnection: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 NT6.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.8Cookies:Bdshare_firstime=1443768140949; uuid_tt_dd=5028529250430960147_20151002;... Omitted

It is easy to see my blog address http://blog.csdn.net/itachi85, the requested method is get, because it is a get method so there is no request for data.

Response message:

http/1.1  $Ok//Status lineServer:openresty//Response headerDate: Sun, -Mar .  ,: -: WuGmtcontent-type: text/html; CharSet=Utf-8Transfer-encoding: Chunkedconnection:keep-aliveKeep-alive: timeout= -Vary:accept-encodingCache-control:PrivateX-powered-by: PHP5.4.Content-encoding: gzip//spaces that cannot be omitted -B5}ysi1? FSGL N- ]{^_ {' z! C, m# 0!l ' 4x ly.?  * ZAT_XL * 9 ' O?   ‘ ? 3 ^1a ... Omitted

Response message nothing to say, next we configure the mobile network agent, access to an application interface

Request message:

POST http://patientapi.shoujikanbing.com/api/common/getversion http/1.1//Request LineContent-length:226                                                          //Request HeaderContent-type: application/x-www-form-urlencodedHost:patientapi.Shoujikanbing.Comconnection:keep-aliveUser-agent: mozilla/5.0(Linux; U Android4.4. 4; Zh-CN; MI NOTELTEbuild/ktu84p) applewebkit/533.1(khtml, like Gecko) version/4.0Mobile safari/533.1Accept-encoding: gzip//cannot omit the space, the following is the request dataClientVersion=2_2. 0. 0&Time=1459069342&AppId=Android&Channel=Hjwang&SessionId=0D1cee1f31926ffa8894c64804efa855101d56eb21caf5db5dcb9a4955b7fbc9&Token=b191944d680145b5ed97f2f4ccf03058&DeviceId=869436020220717&type=2&Version=2.0. 0

From the request line of the request message, the method of the request is post, the request address is http://patientapi.shoujikanbing.com/api/common/getVersion, it is obviously the interface to obtain the version information.

Response message:

http/1.1  $Ok//Status lineServer:nginx//Response headerDate: Sun, -Mar .  the: Geneva: -Gmtcontent-type: Text/html;charset=Utf-8Transfer-encoding: Chunkedconnection:keep-aliveVary:accept-encodingSet-cookie: SessionId=0D1CEE1F31926FFA8894C64804EFA855101D56EB21CAF5DB5DCB9A4955B7FBC9; Expires=Mon, --mar- .  the: Geneva: -GMT;Max-age=86400; Path=/; Domain=.Shoujikanbing.ComSet-cookie: PHPSESSID=0D1CEE1F31926FFA8894C64804EFA855101D56EB21CAF5DB5DCB9A4955B7FBC9; Path=/; Domain=.Shoujikanbing.Comexpires:thu, +Nov1981  ,: the:xxGmtCache-control: No-store, no-cache, must-revalidate, post-check=0, Pre-check=0Pragma:no-cacheContent-encoding: gzip//spaces that cannot be omitted -F//Entity message encoding format for gzip so the response data shown here is garbledMP N @"E?" N M 1 W (HL (1^ P nK E? 3gNLH 7P $c \ T 4a6 l:+ 1dy% $g h H + ... Omitted

The entity that responds to the message uses the encoding format for gzip, so the Fiddler software displays garbled characters.

Android Network Programming (i) HTTP protocol principle

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.