7.1.2 Study of Android HTTP Request and Response Headers
Category Android Basic Tutorial
Introduction to This Section:
>
In the previous section, we gained an understanding of network programming involved in Android and also learned the basic concepts of HTTP. In this section, we will study the HTTP request and response headers. Of course, you can also consider this section as a document to refer to when needed!
1. HTTP Request Message Headers:
>
Here is the figure provided in the last section. Based on the table given below, let's all feel the role of the related request headers: PS: The first line is the request line: request method + resource name + HTTP protocol version number. In addition, the request header is just a piece of information for the server or a simple one. As for how to handle it, it is still decided by the server!
HTTP Request Header Information Comparison Table:
Header | Explanation | Example |
---|---|---|
Accept | Specifies the content types that the client can accept | Accept: text/plain, text/html |
Accept-Charset | The character encodings that the browser can accept. | Accept-Charset: iso-8859-5 |
Accept-Encoding | Specifies the web server return content compression encoding types that the browser can support. | Accept-Encoding: compress, gzip |
Accept-Language | The languages that the browser can accept. | Accept-Language: en,zh |
Accept-Ranges | Can request one or more sub-range fields of the web page entity | Accept-Ranges: bytes |
Authorization | HTTP authorization credential | Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Cache-Control | Specifies the caching mechanism that the request and response should follow | Cache-Control: no-cache |
Connection | Indicates whether a persistent connection is required. (HTTP 1.1 defaults to persistent connection) | Connection: close |
Cookie | When the HTTP request is sent, all the cookie values saved under the domain name of the request are sent to the web server. | Cookie: $Version=1; Skin=new; |
Content-Length | The length of the request content | Content-Length: 348 |
Content-Type | The MIME information corresponding to the request entity | Content-Type: application/x-www-form-urlencoded |
Date | The date and time when the request was sent | Date: Tue, 15 Nov 2010 08:12:31 GMT |
Expect | The specific server behavior requested | Expect: 100-continue |
From | The user's email that sent the request | From: [email protected] |
Host | Specifies the domain name and port number of the server for the request | Host: www.zcmhi.com |
If-Match | Only valid if the request content matches the entity | If-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Modified-Since | If the requested part has been modified after the specified time, the request is successful; if not modified, return code 304 | If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
If-None-Match | If the content has not changed, return code 304. The parameter is the ETag previously sent by the server, and it is compared with the ETag in the server's response to determine if it has changed | If-None-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Range | If the entity has not changed, the server sends the part that the client has lost; otherwise, it sends the entire entity. The parameter is also ETag | If-Range: "737060cd8c284d8af7ad3082f209582d" |
If-Unmodified-Since | Only if the entity has not been modified after the specified time, the request is successful | If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
Max-Forwards | Limits the time the message is forwarded through proxies and gateways | Max-Forwards: 10 |
Pragma | Used to include implementation-specific directives | Pragma: no-cache |
Proxy-Authorization | Authorization credential for connecting to a proxy | Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Range | Only request a part of the entity, specifying the range | Range: bytes=500-999 |
Referer | The address of the previous web page, the current requested web page follows it, that is, the source | Referer: http://blog |
import java.io.OutputStream;
import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class ServletOne extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
/**
- Running result: *
- When we visit: http://localhost:8080/HttpTest/ServletOne, we find that the page redirects to Baidu.
- Then we use the Firefox developer tool: we can see the content of the HTTP request we sent: * */
2) Tell the browser the data compression format through Content-Encoding
Implementation code:
package com.jay.http.test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletTwo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String data = "Fresh air and sunshine can have an amazing effect on our feelings. "
+ "Sometimes when we are feeling down, all that we need to do is simply to go "
+ "outside and breathe. Movement and exercise is also a fantastic way to feel better. "
+ "Positive emotions can be generated by motion. So if we start to feel down,"
+ " take some deep breathes, go outside, feel the fresh air, "
+ "let the sun hit our face, go for a hike, a walk, a bike ride, "
+ "a swim, a run, whatever. We will feel better if we do this.";
System.out.println("Original data length: " + data.getBytes().length);
// Compress the data:
ByteArrayOutputStream bout = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(bout);
gout.write(data.getBytes());
gout.close();
// Get the compressed data
byte gdata[] = bout.toByteArray();
resp.setHeader("Content-Encoding", "gzip");
resp.setHeader("Content-Length", String.valueOf(gdata.length));
resp.getOutputStream().write(gdata);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
};
}
Running result:
Console output:
Browser output:
Let's take a look at our HTTP content again:
This gzip compression string is not very efficient for simple string compression. For example, Xiaozhu originally wrote a string of a quiet night poem, and later found that the size after compression was actually larger than the original =-=...
3) Set the type of data returned through the content-type
>
Sometimes the server may return a text/html, sometimes it may be an image/jpeg, or a video video/avi. The browser can display the data in different ways according to this corresponding data type! Well, here we make a PDF reader.
Implementation code:
package com.jay.http.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletThree extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setHeader("content-type", "application/pdf");
InputStream in = this.getServletContext().getResourceAsStream("/file/android编码规范.pdf");
byte buffer[] = new byte[1024];
int len = 0;
OutputStream out = resp.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
doGet(req, resp);
};
}
Running result:
Enter in the browser: http://localhost:8080/HttpTest/ServletThree
Okay, it can indeed read PDFs. By the way, I have put this PDF in the file directory under webroot, otherwise it will report a null pointer oh ~:
Of course, you can also try to play a piece of music or video, just change the content-type parameter.
Here is a list of HTTP Content-type for your reference: HTTP Content-type comparison table
4) Let the browser redirect to another page after a few seconds through the refresh response header
Well, we may have such a need, such as refreshing the page every few seconds, or loading a page and then redirecting to another page a few seconds later, then refresh can meet your needs~
Implementation code:
package com.jay.http.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
public class ServletFive extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setHeader("content-disposition", "attachment;filename=Android.pdf");
InputStream in = this.getServletContext().getResourceAsStream("/file/android编码规范.pdf");
byte buffer[] = new byte[1024];
int len = 0;
OutputStream out = resp.getOutputStream();
while((len = in.read(buffer)) > 0)
{
out.write(buffer,0,len);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
Running Result :
Summary of This Section:
>
This section introduced the request headers and response headers in Http, and also provided several examples of adjusting the browser with response headers. I believe that after this chapter, you have a better understanding of the Http protocol. Next, we will learn about the Http request method provided by Android: HttpURLConnection! That's it for this section, thank you~ By the way, the demo for this section can be downloaded: Download HttpTest.zip
-1.0 Android Basic Tutorial for Beginners
-1.0.1 Latest Android Basic Tutorial Catalog for 2015
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android APP with Eclipse + ADT + SDK
-1.2.2 Developing Android APP with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-1.5.1 Git Tutorial on Basic Operations of Local Repositories
-1.5.2 Git: Using GitHub to Set Up a Remote Repository
-1.6 How to Play with 9 (Jiu Mei) Images
-1.7 Interface Prototype Design
-1.8 Project-Related Analysis (Various Files, Resource Access)
-1.9 Android Program Signing and Packaging
-1.11 Decompiling APK to Retrieve Code & Resources
-2.1 Concept of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 TextView (Text Box) Detailed Explanation
-2.3.2 EditText (Input Box) Detailed Explanation
-2.3.3 Button (Button) and ImageButton (Image Button)
-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)
-2.3.7 ProgressBar (Progress Bar)
-2.3.9 RatingBar (Star Rating Bar)
-2.4.1 ScrollView (Scroll View)
-2.4.2 Date & Time Components (Part 1)
-[2.4.3 Date & Time Components (Part
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Fragment Example - Bottom Navigation Bar Implementation (Method 1)
5.2.2 Fragment Example - Bottom Navigation Bar Implementation (Method 2)
5.2.3 Fragment Example - Bottom Navigation Bar Implementation (Method 3)
5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager Page Swiping
5.2.5 Fragment Example - Simple Implementation of News (Shopping) App List Fragment
6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
7.1.1 Android Network Programming and Http Protocol Learning
7.1.2 Learning Android Http Request and Response Headers
11.0 "2015 Latest Android Basic Tutorial" Concludes with Celebration
12.2 DrySister Girl Viewing App (First Edition) — 2. Parsing Backend Data
12.4 DrySister Girl Viewing App (First Edition) — 4. Adding Data Caching (Integrating SQLite)