1. HTTP请求内容分析
2. HTTP响应内容分析
3. 请求头和响应头的读取
1. HTTP请求内容分析
用Chrome打开网址 http://www.marschen.com/data1.html
打开开发者工具, 刷新页面之后会出现下述状况. data1.html就是发往服务器的请求
双击打开data1.html
请求头内容详解
响应头内容详解
3. 请求头和响应头的读取
1 class NetworkThread extends Thread{ //主线程不能访问网路!!! 2 @Override 3 public void run() { 4 HttpClient httpClient = new DefaultHttpClient(); 5 HttpGet httpGet = new HttpGet("http://www.marschen.com/data1.html"); 6 //请求头是自己添加的,以键值对的形式 7 //只添加一个Accept-language作为示范, 打印时应该只是一个请求头 8 httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4"); 9 Header [] reqHeader = httpGet.getAllHeaders(); //键值对 10 for (int i = 0; i < reqHeader.length; i++) { 11 String name = reqHeader[i].getName(); 12 String value = reqHeader[i].getValue(); 13 Log.d("HTTP","Http request: Name--->" + name + ",Value--->" + value); 14 } 15 try { 16 HttpResponse resp = httpClient.execute(httpGet); 17 //响应头是服务器返回的,也是键值对形式 18 Header [] respHeader = resp.getAllHeaders(); 19 for (int i = 0; i < respHeader.length; i++) { 20 String name = respHeader[i].getName(); 21 String value = respHeader[i].getValue(); 22 Log.d("HTTP","Http response: Name--->" + name + ",Value--->" + value); 23 } 24 25 //检查相应的状态是否正常, 检查状态码是否是200 26 int code = resp.getStatusLine().getStatusCode(); 27 if(code == 200){ 28 //从相应对象中取值,得到的是流对象 29 HttpEntity entity = resp.getEntity(); 30 InputStream in = entity.getContent(); 31 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 32 String line = reader.readLine(); 33 Log.d("HTTP","Got From Server: " + line); 34 } 35 } 36 catch (Exception e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } 40 } 41 }