上節(jié)中我們對Android涉及的網(wǎng)絡編程進行了了解,也學習了下Http的基本概念,而本節(jié)我們 要學習的是Http的請求頭與響應頭,當然,可以把也可以把這節(jié)看作文檔,用到的時候來查查 即可!
這里貼下上一節(jié)給出的圖,根據(jù)下面給出的表,大家自己感受下相關請求頭的作用吧: PS:第一行是請求行:請求方式 + 資源名稱 + HTTP協(xié)議版本號,另外請求頭只是給服務端的一個 信息而已或者說一個簡單,至于怎么處理,還是由服務端來決定的!
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 | 可以請求網(wǎng)頁實體的一個或者多個子范圍字段 | Accept-Ranges: bytes |
Authorization | HTTP授權的授權證書 | Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Cache-Control | 指定請求和響應遵循的緩存機制 | Cache-Control: no-cache |
Connection | 表示是否需要持久連接。(HTTP 1.1默認進行持久連接) | Connection: close |
Cookie | HTTP請求發(fā)送時,會把保存在該請求域名下的所有cookie值一起發(fā)送給web服務器。 | Cookie: $Version=1; Skin=new; |
Content-Length | 請求的內容長度 | Content-Length: 348 |
Content-Type | 請求的與實體對應的MIME信息 | Content-Type: application/x-www-form-urlencoded |
Date | 請求發(fā)送的日期和時間 | Date: Tue, 15 Nov 2010 08:12:31 GMT |
Expect | 請求的特定的服務器行為 | Expect: 100-continue |
From | 發(fā)出請求的用戶的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代碼,參數(shù)為服務器先前發(fā)送的Etag,與服務器回應的Etag比較判斷是否改變 | If-None-Match: "737060cd8c284d8af7ad3082f209582d" |
If-Range | 如果實體未改變,服務器發(fā)送客戶端丟失的部分,否則發(fā)送整個實體。參數(shù)也為Etag | If-Range: "737060cd8c284d8af7ad3082f209582d" |
If-Unmodified-Since | 只在實體在指定時間之后未被修改才請求成功 | If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
Max-Forwards | 限制信息通過代理和網(wǎng)關傳送的時間 | Max-Forwards: 10 |
Pragma | 用來包含實現(xiàn)特定的指令 | Pragma: no-cache |
Proxy-Authorization | 連接到代理的授權證書 | Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Range | 只請求實體的一部分,指定范圍 | Range: bytes=500-999 |
Referer | 先前網(wǎng)頁的地址,當前請求網(wǎng)頁緊隨其后,即來路 | Referer: http://blog.csdn.net/coder_pig |
TE | 客戶端愿意接受的傳輸編碼,并通知服務器接受接受尾加頭信息 | TE: trailers,deflate;q=0.5 |
Upgrade | 向服務器指定某種傳輸協(xié)議以便服務器進行轉換(如果支持) | Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 |
User-Agent | User-Agent的內容包含發(fā)出請求的用戶信息 | User-Agent: Mozilla/5.0 (Linux; X11) |
Via | 通知中間網(wǎng)關或代理服務器地址,通信協(xié)議 | Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) |
Warning | 關于消息實體的警告信息 | Warn: 199 Miscellaneous warning |
同樣給出上節(jié)的圖: PS:第一行依次是:協(xié)議版本號 狀態(tài)碼 302表示這里沒有,但是另外一個地方有,通過Location頁面重定向了
Header | 解釋 | 示例 |
---|---|---|
Accept-Ranges | 表明服務器是否支持指定范圍請求及哪種類型的分段請求 | Accept-Ranges: bytes |
Age | 從原始服務器到代理緩存形成的估算時間(以秒計,非負) | Age: 12 |
Allow | 對某網(wǎng)絡資源的有效的請求行為,不允許則返回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 | 在整個返回體中本部分的字節(jié)位置 | Content-Range: bytes 21010-47021/47022 |
Content-Type | 返回內容的MIME類型 | Content-Type: text/html; charset=utf-8 |
Date | 原始服務器消息發(fā)出的時間 | 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 | 包括實現(xiàn)特定的指令,它可應用到響應鏈上的任何接收方 | Pragma: no-cache |
Proxy-Authenticate | 它指出認證方案和可應用到代理的該URL上的參數(shù) | Proxy-Authenticate: Basic |
好了,看了那么多概念的東西,不動動手怎么行呢?是吧,那我們就寫一些簡單的代碼來驗證一些 常用的響應頭的作用吧,以便加深我們的了解,這里的話服務端就用最簡單的Servlet來實現(xiàn),如果不會 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>
改成對應的類名即可!
實現(xiàn)代碼:
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的時候,我們會發(fā)現(xiàn)頁面跳轉到了百度, 接著我們用FireFox的開發(fā)者工具:可以看到我們發(fā)出的HTTP的內容:
實現(xiàn)代碼:
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("原始數(shù)據(jù)長度:" + data.getBytes().length);
// 對數(shù)據(jù)進行壓縮:
ByteArrayOutputStream bout = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(bout);
gout.write(data.getBytes());
gout.close();
// 得到壓縮后的數(shù)據(jù)
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壓縮字符串對于簡單的字符串壓縮,效率不高,比如小豬本來寫的是一個一首靜夜詩的字符串, 后來發(fā)現(xiàn)壓縮過后的大小,竟然比原先的還要大=-=...
服務端返回的有時可能是一個text/html,有時也可能是一個image/jpeg,又或者是一段視頻video/avi 瀏覽器可以根據(jù)這個對應的數(shù)據(jù)類型,然后以不同的方式將數(shù)據(jù)顯示出來!好吧,這里我們弄一個讀PDF的
實現(xiàn)代碼:
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編碼規(guī)范.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這個參數(shù)而已
下面順便給出個HTTP Content-type的對照表吧: HTTP Content-type的對照表
恩呢,一般我們可能有這樣的需求,比如每隔幾秒刷新一次頁面,又或者加載某個頁面幾秒后 又跳轉至另一個頁面,那么refresh可以滿足你的需要~
實現(xiàn)代碼:
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秒刷新一次頁面,我們可以看到顯示的數(shù)字是遞增的,另外doGet方法也一直被調用, 說明頁面真的是刷新的!
- 2的話進入頁面后5s,就自己跳轉到百度了~
這個很簡單,我們只需把③中設置Content-type的一行去掉,然后加上: resp.setHeader("content-disposition", "attachment;filename=Android.pdf");
實現(xiàn)代碼:
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編碼規(guī)范.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);
}
}
運行結果:
本節(jié)給大家介紹了Http中的請求頭和響應頭,也寫了幾個關于響應頭調瀏覽器的一些示例, 相信經過本章,大家對于Http協(xié)議更加了解了,下節(jié)我們來學習Android給我們提供的Http 請求方式:HttpURLConnection!好的,本節(jié)就到這里,謝謝~ 對了,本節(jié)demo下載:下載 HttpTest.zip
更多建議: