Learning about Android Http request headers and response headers


Introduction to this section:

In the previous section we learned about the network programming involved in Android, and also learned the basic concepts of Http, and in this section we What you need to learn are the request headers and response headers of Http. Of course, you can treat this section as a document and check it out when you need it. That’s it!


1.HTTP request header:

The picture given in the previous section is posted here. According to the table given below, you can feel it for yourself Let’s take a look at the functions of the relevant request headers: PS: The first line is the request line: request method + resource name + HTTP protocol version number. In addition, the request header is only one for the server. It's just information or a simple one. As for how to process it, it's up to the server to decide!

1.png


HTTP Request Header request header information comparison table:

The language accepted by the browserAccept-Language: en,zhYou can request one or more sub-range fields of the web page entityAccept-Ranges: bytes##AuthorizationCache-ControlConnectionCookieOnly when the entity is The request is successful only if it has not been modified after the specified timeIf-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMTLimit the time that information is sent through proxies and gatewaysMax-Forwards: 10Used to contain implementation-specific directivesPragma: no-cache##Proxy-AuthorizationRangeReferer##TETE: trailers,deflate;q=0.5UpgradeUpgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11User-AgentUser-Agent: Mozilla/5.0 (Linux; X11 )ViaVia: 1.0 fred, 1.1 nowhere. com (Apache/1.1)##Warning
HeaderExplanationExample
AcceptSpecify the content type that the client can receiveAccept: text/plain, text /html
Accept-CharsetThe character encoding set that the browser can accept. Accept-Charset: iso-8859-5
Accept-EncodingSpecify the web server that the browser can support Returns the content compression encoding type. Accept-Encoding: compress, gzip
##Accept-Language
Accept-Ranges
HTTP authorization authorization certificateAuthorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Specify the caching mechanism followed by requests and responsesCache-Control: no-cache
Indicates whether a persistent connection is required. (HTTP 1.1 makes a persistent connection by default) Connection: close
When the HTTP request is sent, it will be saved All cookie values ​​under the requested domain name are sent to the web server together.Cookie: $Version=1; Skin=new;
Content-LengthRequested content lengthContent-Length: 348
Content-TypeThe requested MIME information corresponding to the entity Content-Type: application/x-www-form-urlencoded
DateThe date and time the request was sent Date: Tue, 15 Nov 2010 08:12:31 GMT
ExpectRequested specific server behavior Expect: 100-continue
FromThe email of the user who made the requestFrom: user@email.com
HostSpecify the domain name and port number of the requested serverHost: www.zcmhi.com
If-MatchOnly valid if the request content matches the entityIf-Match: "737060cd8c284d8af7ad3082f209582d"
If-Modified-SinceIf the requested part is modified after the specified time, the request is successful. If it has not been modified, a 304 code is returnedIf-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-MatchIf the content is not The change returns a 304 code. The parameter is the Etag previously sent by the server. Compare it with the Etag responded by the server to determine whether it has changed. If-None-Match: "737060cd8c284d8af7ad3082f209582d"
If-RangeIf the entity has not changed, the server sends the part that the client lost, otherwise sends the entire entity.The parameter is also EtagIf-Range: "737060cd8c284d8af7ad3082f209582d"
##If-Unmodified-Since
Max-Forwards
Pragma
Connection Authorization certificate to proxy Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Only request part of the entity, Specify rangeRange: bytes=500-999
The address of the previous web page, followed by the current requested web page Afterwards, the source is Referer: http://blog.csdn.net/coder_pig
The transfer encoding that the client is willing to accept, and notifies the server to accept the tail plus header information
Specify a transport protocol to the server for conversion (if supported)
The content of User-Agent contains information about the user who made the request
Notify the intermediate gateway or proxy server address, communication protocol
Warning information about message entitiesWarn: 199 Miscellaneous warning

2.Response header of HTTP response:

Also gives the picture in the previous section: PS: The first line is: protocol version number, status code 302 means it is not available here, but it is available in another place, and it is redirected through the Location page

2.png

HTTP Responses Header Response header information comparison table:

# will be returned. ##Allow: GET, HEAD##Cache-ControlContent-Encoding##Content-LanguageContent-Language: en,zh Content-LengthContent-Length: 348Content-LocationContent-Location: /index.htmContent-MD5Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==Content-RangeContent-Range: bytes 21010-47021/47022Content-TypeContent-Type: text/html; charset=utf-8DateDate: Tue, 15 Nov 2010 08:12:31 GMTETagETag: "737060cd8c284d8af7ad3082f209582d"ExpiresExpires: Thu, 01 Dec 2010 16:00:00 GMTLast-ModifiedLast-Modified: Tue, 15 Nov 2010 12:45:26 GMTLocation
HeaderExplanationExample
Accept-RangesIndicates whether the server supports specified range requests and which type of segmented requestsAccept -Ranges: bytes
AgeEstimated time (in seconds, non-negative) from origin server to proxy cache formation Age: 12
AllowA valid request behavior for a certain network resource. If it is not allowed, 405
Tell all caching mechanisms whether they can be cached and what typeCache-Control: no-cache
The returned content compression encoding type supported by the web serverContent-Encoding: gzip
The language of the response body
The length of the response body
Request an alternative address for the resource
Returns the MD5 check value of the resource
The byte position of this part in the entire return body
Return the MIME type of the content
Time when the original server message was sent
The current value of the entity tag of the request variable
Response expiration date and time
The last modified time of the requested resource
Used to redirect the recipient to the location of the non-requested URL to complete the request or identify a new resourceLocation: http://blog.csdn.net/coder_pig
PragmaIncludes implementation-specific directives that can be applied to any receiver on the response chainPragma: no-cache
Proxy-AuthenticateIt indicates the authentication scheme and parameters that can be applied to the proxy on that URLProxy-Authenticate: Basic

3. The role of the code verification response header:

Okay, after reading so many concepts, how can I do it without taking action? Right, then let's write some simple code to verify some Let’s take a look at the functions of commonly used response headers in order to deepen our understanding. Here, the server will use the simplest Servlet to implement it. If not Java Web friends only need to copy the code, configure web.xml, and add the Servlet class name, such as:

FirstServletcom.jay.server.FirstServletFirstServlet/FirstServlet

to the corresponding class name!


1) Implement page redirection through Location

Implementation code:

package com.jay.http.test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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 {
		//告诉浏览器响应码,以及重定向页面
		resp.setStatus(302);
		resp.setHeader("Location", "http://www.baidu.com");
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}

Running result:

When we visit: http://localhost:8080/HttpTest/ServletOne, we will find that the page jumps to Baidu, Then we use FireFox’s developer tools: you can see the content of the HTTP we sent:

3.png

2) Tell the browser the compression format of the data 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("原始数据长度:" + data.getBytes().length);
		// 对数据进行压缩:
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		GZIPOutputStream gout = new GZIPOutputStream(bout);
		gout.write(data.getBytes());
		gout.close();
		// 得到压缩后的数据
		byte gdata[] = bout.toByteArray();
		resp.setHeader("Content-Encoding", "gzip");
		resp.setHeader("Content-Length", gdata.length + "");
		resp.getOutputStream().write(gdata);

	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	};
}

Running result:

4.png

##Console output:

5.png

Browser output:

6.png

This

gzip compressed string is not efficient for simple string compression. For example, Xiaozhu originally wrote a string of poems about a quiet night. Later, I found that the compressed size was even larger than the original one =-=...


3) Set the returned data type through content-type

What the server returns may sometimes be a text/html, sometimes it may be an image/jpeg, or a video/avi The browser can display the data in different ways according to the corresponding data type! Okay, here we get a

implementation code for reading PDF:

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 on the browser: http://localhost:8080/HttpTest/ServletThree

Okay, you can indeed read the PDF. By the way, I have lost this PDF in the file directory of the webroot, otherwise it will Report a null pointer~:

Of course, you can also try to play a piece of music or video, just modify the content-type parameter

The following is an HTTP Content- Type comparison table:

HTTP Content-type comparison table7.png


4) Use the refresh response header to let the browser jump to another page after a few seconds

Well, generally we may have such a need, such as every few seconds Refresh the page every second, or a few seconds after loading a page Jump to another page, 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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletFour extends HttpServlet {
	public int second = 0;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.浏览器每隔2秒定时刷新页面
//		resp.setHeader("refresh", "2");
//		resp.getWriter().write(++second + "");
//		System.out.println("doGet方法被调用~");
		
		//2.进入页面5s后,然页跳到百度~
		resp.setHeader("refresh", "5;url='http://www.baidu.com'");
		resp.getWriter().write("HE HE DA~");
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException 
	{
		doGet(req, resp);
	};
}

Running result:

  • 1 If the page is refreshed every 2 seconds, we can see that the displayed number is increasing, and the doGet method is also called all the time. The description page is really refreshed! If
  • 2, 5 seconds after entering the page, you will jump to Baidu~

##5) Let the browser download the file through the content-dispostion response header

This is very simple. We only need to remove the line that sets Content-type in ③, and then add:

resp.setHeader("content-disposition", "attachment;filename=Android .pdf");

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 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:

8.png


Summary of this section:

This section introduces you to the request headers and response headers in Http, and also writes a few tips about adjusting the browser using response headers. some examples, I believe that after this chapter, everyone has a better understanding of the Http protocol. In the next section, we will learn about the Http provided by Android. Request method: HttpURLConnection! Okay, that’s it for this section, thank you~ By the way, download the demo of this section:

Download HttpTest.zip