本節引言:
上節中我們對Android涉及的網絡編程進行了了解,也學習了下Http的基本概念,而本節我們 要學習的是Http的請求頭與響應頭,當然,可以把也可以把這節看作文檔,用到的時候來查查 即可!
1.HTTP請求之消息頭:
根據下面給出的表,大家自己感受一下相關相關請求頭的作用吧:PS:第一行是請求行:請求方式+資源名稱 + HTTP協議版本號,另外請求只是給服務端的一個信息而已或者說一個簡單的,至於怎么處理還是由服務端來決定的!
HTTP Request Header請求頭信息對照表:
Header |
解釋 | 示例 |
---|---|---|
Accept | 指定客戶端能夠接收的內容類型 | Accept: text/plain, text/html |
Accept-Charset | 瀏覽器可以接受的字符編碼集。 | Accept-Charset: iso-8859-5 |
Accept-Encoding | 指定瀏覽器可以支持的web服務器返回內容壓縮編碼類型。 | Accept-Encoding: compress, gzip |
Accept-Language | 瀏覽器可接受的語言 | Accept-Language: en,zh |
Accept-Ranges | 可以請求網頁實體的一個或者多個子范圍字段 | Accept-Ranges: bytes |
Authorization | HTTP授權的授權證書 | Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Cache-Control | 指定請求和響應遵循的緩存機制 | Cache-Control: no-cache |
Connection | 表示是否需要持久連接。(HTTP 1.1默認進行持久連接) | Connection: close |
Cookie | HTTP請求發送時,會把保存在該請求域名下的所有cookie值一起發送給web服務器。 | Cookie: $Version=1; Skin=new; |
Content-Length | 請求的內容長度 | Content-Length: 348 |
Content-Type | 請求的與實體對應的MIME信息 | Content-Type: application/x-www-form-urlencoded |
Date | 請求發送的日期和時間 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
Expect | 請求的特定的服務器行為 | Expect: 100-continue |
From | 發出請求的用戶的Email | From: user@email.com |
Host | 指定請求的服務器的域名和端口號 | Host: www.zcmhi.com |
If-Match | 只有請求內容與實體相匹配才有效 | If-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Modified-Since | 如果請求的部分在指定時間之后被修改則請求成功,未被修改則返回304代碼 | If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
If-None-Match | 如果內容未改變返回304代碼,參數為服務器先前發送的Etag,與服務器回應的Etag比較判斷是否改變 | If-None-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Range | 如果實體未改變,服務器發送客戶端丟失的部分,否則發送整個實體。參數也為Etag | If-Range: "737060cd8c284d8af7ad3082f209582d" |
If-Unmodified-Since | 只在實體在指定時間之后未被修改才請求成功 | If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
Max-Forwards | 限制信息通過代理和網關傳送的時間 | Max-Forwards: 10 |
Pragma | 用來包含實現特定的指令 | Pragma: no-cache |
Proxy-Authorization | 連接到代理的授權證書 | Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Range | 只請求實體的一部分,指定范圍 | Range: bytes=500-999 |
Referer | 先前網頁的地址,當前請求網頁緊隨其后,即來路 | Referer: http://blog.csdn.net/coder_pig |
TE | 客戶端願意接受的傳輸編碼,並通知服務器接受接受尾加頭信息 | TE: trailers,deflate;q=0.5 |
Upgrade | 向服務器指定某種傳輸協議以便服務器進行轉換(如果支持) | Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 |
User-Agent | User-Agent的內容包含發出請求的用戶信息 | User-Agent: Mozilla/5.0 (Linux; X11) |
Via | 通知中間網關或代理服務器地址,通信協議 | Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) |
Warning | 關於消息實體的警告信息 | Warn: 199 Miscellaneous warning |
2.HTTP響應之響應頭:
如下圖:PS:第一行依次是:協議版本號 狀態碼 302表示這里沒有,但是另外一個地方有,通過Location頁面重定向了
HTTP Responses Header 響應頭信息對照表:
Header | 解釋 | 示例 |
---|---|---|
Accept-Ranges |
表明服務器是否支持指定范圍請求及哪種類型的分段請求 | Accept-Ranges: bytes |
Age | 從原始服務器到代理緩存形成的估算時間(以秒計,非負) | Age: 12 |
Allow | 對某網絡資源的有效的請求行為,不允許則返回405 | Allow: GET, HEAD |
Cache-Control | 告訴所有的緩存機制是否可以緩存及哪種類型 | Cache-Control: no-cache |
Content-Encoding | web服務器支持的返回內容壓縮編碼類型 | Content-Encoding: gzip |
Content-Language | 響應體的語言 | Content-Language: en,zh |
Content-Length | 響應體的長度 | Content-Length: 348 |
Content-Location | 請求資源可替代的備用的另一地址 | Content-Location: /index.htm |
Content-MD5 | 返回資源的MD5校驗值 | Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ== |
Content-Range | 在整個返回體中本部分的字節位置 | Content-Range: bytes 21010-47021/47022 |
Content-Type | 返回內容的MIME類型 | Content-Type: text/html; charset=utf-8 |
Date | 原始服務器消息發出的時間 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
ETag | 請求變量的實體標簽的當前值 | ETag: "737060cd8c284d8af7ad3082f209582d" |
Expires | 響應過期的日期和時間 | Expires: Thu, 01 Dec 2010 16:00:00 GMT |
Last-Modified | 請求資源的最后修改時間 | Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT |
Location | 用來重定向接收方到非請求URL的位置來完成請求或標識新的資源 | Location: http://blog.csdn.net/coder_pig |
Pragma | 包括實現特定的指令,它可應用到響應鏈上的任何接收方 | Pragma: no-cache |
Proxy-Authenticate | 它指出認證方案和可應用到代理的該URL上的參數 | Proxy-Authenticate: Basic |
3.代碼驗證響應頭的作用:
好了,看了那么多的概念,不動動手怎么行呢,是吧,那我們就寫一些簡單的代碼來驗證一些 常用的響應頭的作用吧,以便加深我們的了解,這里的話服務端就用最簡單的Servlet來實現,如果不會 Java Web的朋友只需將代碼拷一拷,配置下web.xml,把Servlet的類名扣上,比如:
<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>com.jay.server.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/FirstServlet</url-pattern> </servlet-mapping>
改成對應的類名即可
1)通過Location實現頁面重定向
實現代碼:
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); } }
運行結果:當我們去訪問:http://localhost:8080/HttpTest/ServletOne的時候,我們會發現頁面跳轉到了百度, 接着我們用FireFox的開發者工具:可以看到我們發出的HTTP的內容:
2)通過Content-Encoding告訴瀏覽器數據的壓縮格式
實現代碼:
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); }; }
運行結果:
控制台輸出:
瀏覽器輸出:
再看看我們的HTTP內容:
這個gzip壓縮字符串對於簡單的字符串壓縮,效率不高,比如小豬本來寫的是一個一首靜夜詩的字符串, 后來發現壓縮過后的大小,竟然比原先的還要大=-=...
3)通過content-type,設置返回的數據類型
服務端返回的有時可能是一個text/html,有時也可能是一個image/jpeg,又或者是一段視頻video/avi 瀏覽器可以根據這個對應的數據類型,然后以不同的方式將數據顯示出來!好吧,這里我們弄一個讀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); }; }
運行結果:
在瀏覽器上輸入:http://localhost:8080/HttpTest/ServletThree
好噠,果然可以讀到PDF了,對了,這個PDF我已經丟在webroot的file目錄下,不然會報空指針哦~:
當然,你也可以試着去播放一段音樂或者視頻,只需修改下content-type這個參數而已
下面順便給出個HTTP Content-type的對照表吧: HTTP Content-type的對照表
Android代碼的規范
4)通過refresh響應頭,讓瀏覽器隔幾秒后跳轉至別的頁面
一般我們可能有這樣的需求,比如每隔幾秒刷新一次頁面,又或者加載某個頁面幾秒后 又跳轉至另一個頁面,那么refresh可以滿足你的需要~
實現代碼:
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); }; }
運行的結果:
1的話每隔2秒刷新一次頁面,我們可以看到顯示的數字是遞增的,另外doGet方法也一直被調用, 說明頁面真的是刷新的!
2的話進入頁面后5s,就自己跳轉到百度了~
5)通過content-dispostion響應頭,讓瀏覽器下載文件
這個很簡單,我們只需把③中設置Content-type的一行去掉,然后加上: resp.setHeader("content-disposition", "attachment;filename=Android.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 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); } }
運行結果:
本節小結:
本節給大家介紹了Http中的請求頭和響應頭,也寫了幾個關於響應頭調瀏覽器的一些示例, 相信經過本章,大家對於Http協議更加了解了,下節我們來學習Android給我們提供的Http 請求方式:HttpURLConnection!好的,本節就到這里,謝謝~ 對了,本節demo下載:下載 HttpTest.zip