在 Java 網絡編程中,獲取 HTTP 響應頭信息是常見需求。本文詳細演示如何使用 URLConnection 類獲取響應頭,包括獲取所有 Header 字段以及提取特定 Header(如 Server)的方法,並提供完整可運行的示例代碼。
URL obj = new URL("https://www.example.com");
URLConnection conn = obj.openConnection();
Map<String, List<String>> map = conn.getHeaderFields();
getHeaderFields() 返回一個 Map,鍵為 Header 名稱,值為該 Header 的所有值列表(因為 HTTP 允許同名 Header 多次出現)。
List<String> server = map.get("Server");
若 Header 不存在,返回 null,需做非空判斷。
package com.example.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("https://www.bianceng.cn");
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 (Server) \n");
List<String> server = map.get("Server");
if (server == null) {
System.out.println("Key 'Server' is not found!");
} else {
for (String value : server) {
System.out.println(value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
顯示響應Header信息...
Key : null ,Value : [HTTP/1.1 200 OK]
Key : X-Pingback ,Value : [https://www.bianceng.cn/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)
URLConnection 是 Java 標準庫中處理 HTTP 請求的基礎類,無需第三方依賴。HTTP/1.1 200 OK) 的 Key 為 null。conn.setConnectTimeout(5000); conn.setReadTimeout(5000);