Network of Android series (ii) ---- HTTP request header and Response Header

Source: Internet
Author: User
Tags unsupported

First, the HTTP header is introduced:

Correctly setting the HTTP header information can help search engines determine web pages and improve website access speed. Generally, the HTTP message includes a request message from the client to the server and a response message from the server to the client. The client sends a request to the server. The request header contains the method, URI, protocol version, and MIME-like message structure containing the request modifier, client information, and content. The server responds with a status line. The corresponding content includes the version of the message protocol, the success or error code plus the server information, entity meta information, and possible entity content.



The Http protocol defines many methods for interacting with the server, that is, the most basic types of HTTP requests are 4 types, which are GET, POST, PUT, and DELETE. A URL address is used to describe a resource on the network, and GET, POST, PUT, and DELETE in HTTP correspond to the four operations of checking, modifying, adding, and deleting this resource. The most common ones are GET and POST.

GET: Get the resource by requesting the URI. Generally used to get / query resource information.
POST: Used to submit new content to the server. Generally used to update resource information.
 

Interpretation of HTTP header information:

HTTP header fields include four parts: general header, request header, response header and entity header. Each header field consists of a domain name, a colon (:), and a domain value (to put it plainly, it is a key-value pair).

General header: It is a header that can be used by both the client and the server. It can provide some very useful general functions between the client, the server, and other applications, such as the Date header.
Request headers: They are unique to request messages. They provide the server with some additional information, such as what type of data the client wants to receive, such as the Accept header.
Response header: It is convenient for the client to provide information, such as what type of server the client is interacting with, such as the Server header.
Entity header: Refers to the header used to deal with the entity body. For example, the entity header can be used to describe the data type of the entity body, such as the Content-Type header.
 

Third, the HTTP universal header:

The general header field contains header fields that are supported by both request and response messages. The general header field includes cache headers Cache-Control, Pragma, and informational headers Connection, Date, Transfer-Encoding, Update, Via.

1.Cache-Control

Cache-Control specifies the caching mechanism that requests and responses follow. Setting Cache-Control in a request message or response message does not modify the cache processing in another message processing. The cache instructions when requested include no-cache, no-store, max-age, max-stale, min-fresh, only-if-cached, and the instructions in the response message include public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, max-age. The meaning of the instructions in each message is as follows:

no-cache: indicates that the request or response message cannot be cached. In fact, it can be stored in the local cache area, but the cache cannot provide it to the client for use before freshness verification with the original server.
no-store: The cache should remove all traces of the document from storage as soon as possible, as it may contain sensitive information.
max-age: The cache cannot return documents whose cache time is longer than the maximum seconds specified by max-age. If it does not exceed the specified seconds, the browser will not send the corresponding request to the server, and the data will be returned directly by the cache. Decide whether to return new data or still be provided by the cache. If the max-stale command is also sent at the same time, the usage period may exceed its expiration time.
min-fresh: The document must be kept fresh for at least the specified seconds in the future, and a cache object whose freshness lifetime is greater than the sum of its current Age and min-fresh values is accepted.
max-stale: indicates that the client can receive expired response messages. If the value of the max-stale message is specified, the client can receive expired response messages that are within the specified value.
only-if-cached: The client will only get a copy if there is a copy in the cache.
Public: indicates that the response can be cached by any cache area, and any user can be responded with the cached content.
Private: indicates that all or part of the response message for a single user cannot be processed by the shared cache, and only the cached content can be used to respond to the user who previously requested the content.
2.Pragma

The Pragma header field is used to contain implementation-specific instructions. The most common is Pragma: no-cache. In the HTTP / 1.1 protocol, it has the same meaning as Cache-Control: no-cache.

3.Connection

Connection indicates whether a persistent connection is required. If the servlet sees the value "Keep-Alive" here, or sees that the request is using HTTP 1.1 (HTTP 1.1 defaults to persistent connections), it can take advantage of persistent connections when the page contains multiple elements (such as Applet, picture), significantly reducing the time required for download. To achieve this, the servlet needs to send a Content-Length header in the response. The simplest way to do this is to first write the content to a ByteArrayOutputStream and then calculate its size before the content is officially written.

Close: Tells the web server or proxy server to disconnect after completing the response to this request. Do not wait for subsequent requests for this connection.
Keepalive: Tells the web server or proxy server to keep the connection after completing the response to this request and wait for subsequent requests for this connection.
Keep-Alive: If the browser requests to keep the connection, this header indicates how long (seconds) the web server is expected to stay connected, such as Keep-Alive: 300.
4.Date

The Date header field indicates the time when the message was sent. This header should be included in the server response, because the cache is used to evaluate the freshness of the response. The format of the time description is defined by RFC822. For example, Date: Mon, 31 Dec 2001 04:25:57 GMT. The time described by Date represents the world standard time. To convert to local time, you need to know the time zone of the user.

5.Transfer-Encoding

The WEB server indicates how it has encoded the response message body (not the object in the message body), such as whether it is chunked. For example: Transfer-Encoding: chunked

6.Upgrade

It can specify another protocol that may be completely different. For example, an HTTP / 1.1 client can send an HTTP / 1.0 request to the server, which contains an Update header with the value "HTTP / 1.1" so that the client can test the server Whether to use HTTP / 1.1 too.

7.Via

Lists which proxy server the response from the client to OCS or vice versa, and what protocol (and version) they sent the request.

When the client request reaches the first proxy server, the server will add a Via header to its own request and fill in its own relevant information. When the next proxy server receives the request from the first proxy server, it will Copy the Via header of the request from the previous proxy server in the request sent by itself, and add its own information to the back, and so on. When OCS receives the request of the last proxy server, check the Via header, and Know the route that the request traversed. Example: Via: 1.0 236-81.D07071953.sina.com.cn:80 (squid / 2.6.STABLE13)

 

Fourth, the HTTP request header:

The request header is used to indicate who or what is sending the request, where the request originated from, or the preferences and capabilities of the client. The server can try to provide a better response to the client based on the client information given in the request header. The request header field may contain the following fields: Accept, Accept-Charset, Accept-Encoding, Accept-Language, Authorization, From, Host, If-Modified-Since, If-Match, If-None-Match, If-Range, If-Range , If-Unmodified-Since, Max-Forwards, Proxy-Authorization, Range, Referer, User-Agent. The extension of the request header field requires both parties to support it. If there is an unsupported request header field, it will generally be treated as an entity header field.

8.Accept

Tell the web server what media types it accepts, * / * means any type, type / * means all subtypes under that type, type / sub-type.

9.Accept-Charset

The browser tells the server which character set it can receive.

10.Accept-Encoding

The browser declares the encoding method it receives. It usually specifies the compression method, whether it supports compression, and what compression method (gzip, deflate).

11.Accept-Language

The browser declares the language it receives. The difference between language and character set: Chinese is a language, Chinese has many character sets, such as big5, gb2312, gbk, and so on.

12, Authorization

When the client receives a WWW-Authenticate response from the web server, it uses this header to respond to its own authentication information to the web server.

13.If-Match

If the ETag of the object has not changed, it actually means that the object has not changed before performing the requested action to obtain the document.

14.If-None-Match

If the ETag of an object changes, it actually means that the object also changes, and then the requested action is performed to obtain the document.

15.If-Modified-Since

If the requested object is modified after the time specified in the header, the requested action is performed (such as returning the object), otherwise a return code 304 tells the browser that the object has not been modified. Example: If-Modified-Since: Thu, 10 Apr 2008 09:14:42 GMT

16.If-Unmodified-Since

If the requested object has not been modified after the time specified in the header, the requested action is performed (such as returning the object).

17.If-Range

The browser tells the web server that if the object I requested hasn't changed, give me the missing part, and if the object has changed, give me the entire object. The browser sends the ETag of the request object or the last modification time known to the WEB server to let the browser determine whether the object has changed. Always use with Range header.

18.Range

Browsers (such as Flashget multi-threaded downloads) tell the web server which part of the object it wants to fetch. Example: Range: bytes = 1173546

19.Proxy-Authenticate

The proxy server responds to the browser, asking it to provide proxy authentication information.

20.Proxy-Authorization

The browser responds to the authentication request of the proxy server and provides its own identity information.

21.Host

The client specifies the domain name / IP address and port number of the web server he wants to access. Such as Host: rss.sina.com.cn

22.Referer

The browser indicates to the WEB server from which web page URL the URL / URL in the current request was clicked, for example: Referer: http://www.ecdoer.com/

23.User-Agent

The browser identifies itself (which browser it is). Example: Mozilla / 5.0 (Windows NT 6.1) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 36.0.1985.143 Safari / 537.36

 

Five, HTTP response headers:

The response header provides some additional information to the client, such as who is sending the response, the function of the responder, and even some special instructions related to the response. These headers help the client process the response and make better requests in the future. The response header fields include Age, Location, Proxy-Authenticate, Public, Retry-After, Server, Vary, Warning, WWW-Authenticate. The extension of the response header field requires that both parties in the communication support it. If there is an unsupported response header field, it will generally be treated as an entity header field.

24.Age

When the proxy server responds to the request with its own cached entity, this header is used to indicate how long the entity has elapsed since its creation.

25.Server

The web server indicates what software and version it is. For example: Server: Apache / 2.0.61 (Unix)

26.Accept-Ranges

The web server indicates whether it accepts a request to obtain a part of one of its entities (such as a part of a file). bytes: indicates acceptance, none: does not accept.

27, Vary

The web server uses the content of this header to tell the cache server under what conditions can it use the pair returned by this response.
Like responding to subsequent requests. If the source WEB server receives the first request message, its response message header is: Content-Encoding: gzip; Vary: Content-Encoding, then the Cache server analyzes the header of subsequent request messages and checks its Accept- Encoding, whether it is consistent with the Vary header value of the previous response, that is, whether the same content encoding method is used, so as to prevent the Cache server from using the compressed entity in its cache to respond to the browser without the ability to decompress. For example: Vary: Accept-Encoding.

 

Six, HTTP entity header:

The entity header provides a lot of information about the entity and its content, from information about the type of object to various efficient request methods that can use the resource. In short, the entity header can tell the recipient what it is doing. Both the request message and the response message can contain entity information. The entity information generally consists of an entity header field and an entity. The entity header field contains the original information about the entity. The entity header includes the information headers Allow, Location, and the content headers Content-Base, Content-Encoding, Content-Language, Content-Length, Content-Location, Content-MD5, Content- Range, Content-Type, cache header Etag, Expires, Last-Modified, extension-header.

28.Allow

Which request methods are supported by the server (such as GET, POST, etc.).

29.Location

Indicates where the client should go to extract the document, which is used to locate the receiving end on the location (URL) of the resource. Location is usually not set directly, but through the sendRedirect method of HttpServletResponse, which also sets the status code to 302.

30.Content-Base

The base URL to use when parsing relative URLs in the body.

31.Content-Encoding

The web server indicates what compression method (gzip, deflate) it used to compress the objects in the response. For example: Content-Encoding: gzip

32.Content-Language

The web server tells the browser which natural language is most appropriate for understanding the subject.

33.Content-Length

The web server tells the browser the length or size of the object it responds to, for example: Content-Length: 26012

34.Content-Location

Where the resource is physically located.

35.Content-MD5

The subject's MD5 checksum.

36.Content-Range

The entity header is used to specify the insertion position of a part of the entire entity, and it also indicates the length of the entire entity. When the server returns a partial response to the client, it must describe the scope of the response and the entire entity length. General format: Content-Range: bytes-unitSPfirst-byte-pos-last-byte-pos / entity-legth. For example, the form of the first 500 bytes of the transmission header field: Content-Range: bytes0- 499/1234 If an http message contains this section (for example, a response to a range request or an overlapping request to a range of ranges), Content-Range Represents the range of transmission, Content-Length indicates the number of bytes actually transmitted.

37.Content-Type

The web server tells the browser the type of object it responds to. For example: Content-Type: application / xml

38.Etag

Is the flag value of an object (such as a URL). As for an object, such as an html file, if it is modified, its Etag will not be modified. Therefore, the role of ETag is similar to that of Last-Modified, mainly for WEB The server determines whether an object has changed. For example, the last time you requested an html file, you got its ETag. When you request this file again, the browser will send the previously obtained ETag value to the WEB server, and then the WEB server will send this ETag to the current file. ETag is compared, and then you know if this file has changed.

39.Expires

The WEB server indicates when the entity will expire. For expired objects, it can only be used to respond to client requests after verifying its validity with the WEB server. Is the HTTP / 1.0 header. Example: Expires: Sat, 23 May 2009 10:02:12 GMT

40.Last-Modified

The WEB server considers the last modification time of the object, such as the last modification time of the file, the last generation time of the dynamic page, and so on. Example: Last-Modified: Tue, 06 May 2008 02:42:43 GMT

 

Take the Baidu homepage as an example to get the content of the request header and response header:

1. Request header:

We now look at the request header through Google Chrome:

Take the Baidu homepage as an example, then open "Tools-Developer Tools" in Google Chrome, switch to the network tab, and refresh the page:



In the figure above, open the html format file at the arrow, as shown below:



The Request Headers in the picture above are the request headers we need. The contents are all key-value pairs. The server will analyze these key-value pairs after getting them.

Let's repeat the meaning of common request header key-value pairs:

Host: www.baidu.com The host address (virtual host name) of this request
Cache-control: no-cache How to set web cache
Pragma: no-cache
Accept: text / html, xxxxxx… .. The data types that the client can receive (if the content is: * / *, it means to receive all types)
User-Agent: Mozilla / 5.0xxxxx mainly indicates the client type
Accept-Encoding: gzip, deflate, sdch The data compression encoding method that the browser can receive (indicating what format the browser can receive compressed data)
Accept-Language: zh-CN, zh; q = 0.8 Languages accepted by browser
Accept-Charset: ISO-8859-1 character set encoding received by the client
If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT and cache mechanism related headers
Referer: http://www.smyh.me/index.jsp From which page the current page comes from (probably the previous page came to this page through a hyperlink)
Cookies
Connection: close / Keep-Alive after request, whether to close this connection or keep it connected
Date: Tue, 11 Jul 2013 18:23:51 GMT Current requested time
Note: The above refers to the request header of the get request.

 

2. Response header:

Let's look at the contents of the response header again:



Meaning of common response header key-value pairs:

Location: http://www.smyh.me/index.jsp redirection (302 + Location implements redirection)
Server server type
Content-Encoding The data compression format currently returned by the server to the client
Content-Length The amount of data returned to the client
Content-Language: en-US Language
Content-Type: text / html; charset = GB2312 The type of data returned, character set encoding
The last modification time of the Last-Modified resource (coordinate with the If-Modified-Since + 304/307 in the request header to implement the cache mechanism)
Refresh: 1; url = http: //www.it315.org 多少 After a few seconds, which address will the current page visit (for example, after the web page is successfully logged in, it will jump back to the original interface and use this header)
Content-Disposition: attachment; filename = aaa.zip is related to downloading, tells the browser to download the server to send past data as an attachment
Transfer-Encoding: chunked data transfer mode
Set-Cookie: SS = Q0 = 5Lb_nQ; path = / search and cookie-related headers
ETag: W / "83794-1208174400000" cookie-related headers
Expires: -1 tells the browser whether to cache the current resource: if the value of this header is a value in milliseconds, it tells the browser to cache the resource to the specified time point; if the value is 0 or -1, it tells the browser to forbid Caching
Cache-Control: no-cache tells the browser whether to cache resources
Pragma: no-cache-tell the browser whether to cache resources
Note: The reason why the three heads are a function is for historical reasons. Different browsers support these three headers differently. Generally speaking, these three headers should be used simultaneously to ensure that different browsers can implement the cache control function.

Connection: close / Keep-Alive whether to keep the connection
Date: Tue, 11 Jul 2000 18:23:51 GMT Current response time
 

Seven, get the content of the request header and corresponding header through Android code:

In the previous article, we talked about sending HTTP requests using HttpClient. We will copy the code inside and paste it out: (Provincial switch back, troublesome)

The activity_main.xml code is as follows:

Copy code
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
    xmlns: tools = "http://schemas.android.com/tools"
    android: layout_width = "match_parent"
    android: layout_height = "match_parent"
    android: orientation = "vertical"
    tools: context = ". MainActivity">

    <Button
        android: id = "@ + id / button1"
        android: layout_width = "match_parent"
        android: layout_height = "wrap_content"
        android: text = "Send Request" />

    <ScrollView
        android: layout_width = "match_parent"
        android: layout_height = "match_parent">

        <TextView
            android: id = "@ + id / TextView1"
            android: layout_width = "match_parent"
            android: layout_height = "wrap_content"
            android: text = "@ string / hello_world" />
    </ ScrollView>

</ LinearLayout>
Copy code
In the layout file, we use a ScrollView to wrap the TextView. With the help of the ScrollView control, we can allow us to view the part of the i off the screen as soon as we scroll.

The code of MainActivity.java is as follows: (comments are more detailed)

Copy code
 1 package com.example.m04_http01;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.HttpResponse;
 5 import org.apache.http.client.HttpClient;
 6 import org.apache.ht
tp.client.methods.HttpGet;
 7 import org.apache.http.impl.client.DefaultHttpClient;
 8 import org.apache.http.util.EntityUtils;
 9 import android.app.Activity;
10 import android.os.Bundle;
11 import android.os.Handler;
12 import android.os.Message;
13 import android.view.View;
14 import android.view.View.OnClickListener;
15 import android.widget.Button;
16 import android.widget.TextView;
17
18 public class MainActivity extends Activity {
19
20 public static final int SHOW_RESPONSE = 0;
twenty one     
22 private Button button_sendRequest;
23 private TextView textView_response;
twenty four     
25 // Create a new Handler object, receive the Message here, and then update the content of the TextView control
26 private Handler handler = new Handler () {
27
28 @Override
29 public void handleMessage (Message msg) {
30 super.handleMessage (msg);
31 switch (msg.what) {
32 case SHOW_RESPONSE:
33 String response = (String) msg.obj;
34 textView_response.setText (response);
35 break;
36
37 default:
38 break;
39}
40}
41
42};
43
44 @Override
45 protected void onCreate (Bundle savedInstanceState) {
46 super.onCreate (savedInstanceState);
47 setContentView (R.layout.activity_main);
48 textView_response = (TextView) findViewById (R.id.TextView1);
49 button_sendRequest = (Button) findViewById (R.id.button1);
50
51 button_sendRequest.setOnClickListener (new OnClickListener () {
52
53 // When the button is clicked, the thread in the sendRequestWithHttpClient () method is executed
54 @Override
55 public void onClick (View v) {
56 // TODO Auto-generated method stub
57 sendRequestWithHttpClient ();
58}
59});
60}
61
62 // Method: Send a network request to get the data of Baidu's homepage. Start thread in
63 private void sendRequestWithHttpClient () {
64 new Thread (new Runnable () {
65
66 @Override
67 public void run () {
68 // Send request with HttpClient, it is divided into five steps
69 // Step 1: Create HttpClient object
70 HttpClient httpCient = new DefaultHttpClient ();
71 // Step 2: Create the object representing the request, and the parameter is the server address to be accessed
72 HttpGet httpGet = new HttpGet ("http://www.baidu.com");
73
74 try {
75 // The third step: execute the request to obtain the corresponding object returned by the server
76 HttpResponse httpResponse = httpCient.execute (httpGet);
77 // Step 4: Check whether the status of the response is normal: Check that the value of the status code is 200 to indicate normal
78 if (httpResponse.getStatusLine (). GetStatusCode () == 200) {
79 // Fifth step: take the data from the response object and put it in the entity
80 HttpEntity entity = httpResponse.getEntity ();
81 String response = EntityUtils.toString (entity, "utf-8"); // Convert the data in entity to a string
82
83 // Send the Message object in the child thread
84 Message message = new Message ();
85 message.what = SHOW_RESPONSE;
86 message.obj = response.toString ();
87 handler.sendMessage (message);
88}
89
90} catch (Exception e) {
91 // TODO Auto-generated catch block
92 e.printStackTrace ();
93}
94
95}
96)). Start (); // Do not forget this start () method
97
98}
99}
Copy code
The function that this code wants to achieve is: the user clicks the button, can get the html data of Baidu homepage and display in TextView.

Now the thing to do is: modify the content of the sendRequestWithHttpClient () method in the above code:

Copy code
 1 // Method: Send a network request to get the data of Baidu's homepage. Start thread in
 2 private void sendRequestWithHttpClient () {
 3 new Thread (new Runnable () {
 4
 5 @Override
 6 public void run () {
 7 // Send request with HttpClient, it is divided into five steps
 8 HttpClient httpCient = new DefaultHttpClient ();
 9 HttpGet httpGet = new HttpGet ("http://www.baidu.com");
10
11 // The content put into the request header must be in the form of key-value pairs, here Accept-language is taken as an example
12 httpGet.addHeader ("Accept-Language", "zh-CN, zh; q = 0.8, en; q = 0.6, zh-TW; q = 0.4");
13 // Get the request header and receive it with the Header array
14 Header [] reqHeaders = httpGet.getAllHeaders ();
15 // Iterate through the Header array and print it out
16 for (int i = 0; i <reqHeaders.length; i ++) {
17 String name = reqHeaders [i] .getName ();
18 String value = reqHeaders [i] .getValue ();
19 Log.d ("http01", "Http request: Name --->" + name + ", Value --->" + value);
20}
twenty one                 
22 try {
23 HttpResponse httpResponse = httpCient.execute (httpGet);
twenty four                     
25 // Get the response header and receive it with the Header array
26 Header [] responseHeaders = httpResponse.getAllHeaders ();
27 // Iterate through the Header array and print it out
28 for (int i = 0; i <responseHeaders.length; i ++) {
29 String name = responseHeaders [i] .getName ();
30 String value = responseHeaders [i] .getValue ();
31 Log.d ("http01", "Http response: Name --->" + name + ", Value --->" + value);
32}
33
34 if (httpResponse.getStatusLine (). GetStatusCode () == 200) {
35 HttpEntity entity = httpResponse.getEntity ();
36 String response = EntityUtils.toString (entity, "utf-8");
37
38 // Send the Message object in the child thread
39 Message message = new Message ();
40 message.what = SHOW_RESPONSE;
41 message.obj = response.toString ();
42 handler.sendMessage (message);
43}
44
45} catch (Exception e) {
46 // TODO Auto-generated catch block
47 e.printStackTrace ();
48}
49
50}
51)). Start (); // Do not forget this start () method
52
53}
Copy code
In the above code, the bold part is the content we added to get the key-value pairs of the request header and response header. The code is explained as follows:

Line 12: Manually add a request header via the addHeader () method of httpGet

Line 14: Get the content of the response header through the getAllHeaders () method of httpGet and receive it with the Header array. Note that when importing the header package, we chose the org.apache.http.Header package; each key-value pair in the request header is the content in the header.

Lines 16 to 20: traverse the contents of the output Header array.

Lines 25 to 32: Get the content of the response header. The principle is similar.

After running the program and clicking the button, the output in the background is as follows:



This is the same as many of the keys we saw in the previous paragraph.

【Project Files】

Link: http://pan.baidu.com/s/1ntHTYPz

Password: g8vk

 

Reference link:

http://www.ecdoer.com/post/http-seo.html

http://blog.csdn.net/kfanning/article/details/6062118

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.