Android Network Programming (i) HTTP protocol principle

Source: Internet
Author: User

Related articles
Android Network Programming (i) HTTP protocol principle
Android Network Programming (ii) HttpClient and HttpURLConnection
Android Network Programming (iii) Volley use method full analysis
Android Network Programming (iv) parsing from source code volley
Android Network Programming (v) okhttp2.x use method full analysis
Android Network Programming (vi) OKHTTP3 use method full analysis
Android Network Programming (vii) Source code parsing okhttp Previous [request network]
Android Network Programming (eight) source code parsing okhttp [Reuse connection pool]
Android Network Programming (ix) RETROFIT2 prev [Basic use]
Android Network Programming (10) RETROFIT2 [note]
Android Network Programming (11) Source Code parsing retrofit

Preface

This article is the beginning of this series, and as a mobile developer, the development of the application will inevitably be a network interview. Although there are so many open source libraries that can help us to access the Internet easily, we still have to understand the principle of network visit, which is a necessary knowledge point for a good developer. In this article, let's start by understanding the HTTP protocol principle.

1.HTTP Brief Introduction

HTTP is an object-oriented protocol that belongs to the application layer because of its simple, high-speed approach. Applicable to distributed hypermedia information System.

It was introduced in 1990, after several years of use and development. To be constantly intact and extended.

key features of the HTTP protocol
    1. Support C/S (Customer/server) mode.
    2. Simple high speed: When a customer requests a service from the server, it simply transmits the request method and path.

      The request method is often used with, and POST. Each method specifies that the customer has a different type of contact with the server. Because the HTTP protocol is simple, it makes the program of Httpserver small, so the communication speed is very fast.

    3. Flexible: HTTP agrees to transfer arbitrary types of data objects. The type being transmitted is marked by Content-type.

    4. No connection: The meaning of no connection is to limit each connection to just one request. The server finishes processing the customer's request. After receiving the customer's response, 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 assuming that the preceding information may be processed, it must be re-routed, which could result in an increase in the amount of data sent per connection.

      On the other hand, when the server does not need the previous information, it responds faster.

the format of the HTTP URL is as follows
http://host[":"port][abs_path]

HTTP indicates that network resources are to be located through the HTTP protocol, and host represents a legitimate Internet host domain name or IP address. PORT specifies a port number, or null to use the default port of 80. ABS_PATH Specifies the URI of the requested resource (free resources available on the web).
HTTP has two kinds of messages which are request messages and response messages respectively. Let's take a look at the request message first.

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 number of the HTTP protocol. The format is as follows:

Method Request-URI HTTP-Version CRLF

The method means the request, Request-uri is a Uniform resource identifier, the http-version represents the requested HTTP protocol version number, and CRLF represents a carriage return and a newline (except for the CRLF at the end, which does not agree to a separate CR or LF character).

There are 8 methods of HTTP requests. Each is get, POST, DELETE, PUT, HEAD, TRACE, CONNECT, OPTIONS. In which put, DELETE, POST, get respectively corresponding to increase the deletion of the search. The most common use 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 for a response message header for the resource identified by Request-uri
    4. PUT: Requests that the server store a resource. and use Request-uri as its logo
    5. Delete: Request server to delete the resource identified by Request-uri
    6. TRACE: Requests that the server Echo received request information. Mainly used for testing or diagnosis
    7. The connect:http/1.1 protocol is reserved for proxy servers that can change connections to pipelines.
    8. OPTIONS: Request performance for query server. or query for resource-related options and requirements

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

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

There are 0 or more request headers after the request line, and each request header includes a name and a value that is cut with ":" Between them. 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. Instead, it is used in the Post method.

The Post method is useful for situations where customers need to fill out a form, and the most frequently used 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

, http-version represents the version number of the Serverhttp protocol. Status-code represents the response status code sent back by the server. 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. Indicates that the request has been successfully received, understood, accepted
    • 300~399: Redirect to complete the request must be done further
    • 400~499:client error. Request has a syntax error or the request is not implemented
    • 500~599:server side error, server failed to implement legitimate request

Common status codes such as the following:

    • Ok:client Request Success
    • The bad request:client request has a syntax error 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:server received the request. But refused to provide services
    • Internal Server Error:server An unexpected error occurred
    • 503 Server Unavailable:server is currently unable to process client requests. May return to normal after a certain period of time

For example, visit my CSDN blog address the status line of the 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 a pair of key-value pairs, one for each row. Keywords and values are delimited by the English colon ":".

Generic Header

Can be present in the request header, but also in the response header of today

    • Date: Indicates the day and time the message was generated
    • Connection: The option to send the specified connection is accepted. For example, specify that the connection is continuous. Or specify the "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 (a message cache instruction does not affect the caching mechanism for a message processing)
Request Header

The request header notifies the server about client-seeking information, and a typical request header is:

    • Host: The hostname of the request, consent to multiple domain names in the same IP address, that is, the virtual host
    • User-agent: Send requested browser type, operating system and other information
    • Accept:client a list of recognized content types that specifies 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: Agree with the client and server to specify options related to the request/response connection, for example, this is for keep-alive to remain connected.

    • Transfer-encoding: Inform the receiving side in order to ensure the reliable transmission of the message. What encoding is used for the message.
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 used when changing the domain name
    • Server: Includes system information that can be used by the server to process requests. Corresponds to the user-agent request header
Entity Header

The entity header is used to set the information for the transmitted resource, which can be used for both request and response. Both request and response messages are capable of delivering an entity. The common entity headers are:

    • 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, if not set, feels that the entity content will be available to all the languages read
    • Content-encoding: The entity header is used as the modifier for the media type. Its value indicates the encoding of the additional content that has been applied to the entity body, so that 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 date and time the resource was last modified
    • Expires: The entity header gives the date and time the response expires
5. Application Examples

There are a number of ways to view a Web page or a request for a mobile phone requesting a network and a response message, which is recommended using Fiddler, which details how to use the Fiddler in an Android Web data capture using Fiddler. I will not dwell on it here.
Open fiddler and then use your browser to visit 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

Very easy to see the interview is my blog address http://blog.csdn.net/itachi85, the requested method is get, because it is a get method so did not request 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 There is 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 requested method is post and the request address is http://patientapi.shoujikanbing.com/api/common/getVersion. It is obviously the interface that gets the version number 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 ?93‘3gNLH 7P $c \ T 4a6 L:+ 1dY%$g h H +...省略

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

Please pay attention to my public number. The first time to get a blog update reminder. As well as many other Android-related original technical dry goods.
Sweep the QR code below or long press to identify two-dimensional code, you can pay attention to.

Android Network Programming (i) HTTP protocol principle

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.