qiyadeng

专注于Java示例及教程
posts - 84, comments - 152, trackbacks - 0, articles - 34

Java获取Http响应Header信息

Posted on 2013-03-12 21:40 qiyadeng 阅读(11152) 评论(3)  编辑  收藏

本文中演示如何通过URLConnection获取Http响应Header信息

1.从响应中获得Header信息

                
                URL obj = new URL("http://www.qiyadeng.com");
                URLConnection conn 
= obj.openConnection();
                Map
<String, List<String>> map = conn.getHeaderFields();
 

2.从响应Header中获取Server信息

 
               Map<String, List<String>> map = conn.getHeaderFields();
                List
<String> server = map.get("Server");
 

完整的示例

package com.qiyadeng.http;

import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
 
public class GetHttpResponseHeader {
 
  
public static void main(String[] args) {
 
        
try {
 
                URL obj 
= new URL("http://www.qiyadeng.com");
                URLConnection conn 
= obj.openConnection();
                Map
<String, List<String>> map = conn.getHeaderFields();
 
                System.out.println(
"显示响应Header信息\n");
 
                
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        System.out.println(
"Key : " + entry.getKey() + 
                                           
" ,Value : " + entry.getValue());
                }
 
                System.out.println(
"\n使用key获得响应Header信息 \n");
                List
<String> server = map.get("Server");
 
                
if (server == null) {
                        System.out.println(
"Key 'Server' is not found!");
                } 
else {
                        
for (String values : server) {
                                System.out.println(values);
                        }
                }
 
        } 
catch (Exception e) {
                e.printStackTrace();
        }
 
  }
 
}
 

输出

显示响应Header信息...

Key : null ,Value : [HTTP/1.1 200 OK]
Key : X
-Pingback ,Value : [http://www.qiyadeng.com/xmlrpc.php]
Key : Date ,Value : [Sun, 10 Mar 2013 12:16:26 GMT]
Key : Transfer
-Encoding ,Value : [chunked]
Key : Connection ,Value : [close]
Key : Content
-Type ,Value : [text/html; charset=UTF-8]
Key : Server ,Value : [Apache
/2.2.3 (CentOS)]
Key : X
-Powered-By ,Value : [PHP/5.2.17]
使用key获得响应Header信息 ...

Apache/2.2.3 (CentOS)




原创文章,转载请注明: 转载自http://www.qiyadeng.com/

本文链接地址: Java获取Http响应Header信息

Feedback

# re: Java获取Http响应Header信息  回复  更多评论   

2013-03-12 21:46 by 九星天辰诀
只能看懂一部分。

# re: Java获取Http响应Header信息  回复  更多评论   

2013-05-16 17:16 by kevenzhang
thank you very much

# re: Java获取Http响应Header信息[未登录]  回复  更多评论   

2016-01-22 00:08 by 1
1121

只有注册用户登录后才能发表评论。


网站导航: