Java 实例 - 获取 URL 响应头信息

以下实例演示了如何获取指定 URL 的响应头信息:

Main.java 文件

  1. import java.io.IOException;
  2. import java.net.URL;
  3. import java.net.URLConnection;
  4. import java.util.Map;
  5. import java.util.Set;
  6. public class Main {
  7. public static void main(String[] args) throws IOException{
  8. URL url = new URL("http://www.baidu.com");
  9. URLConnection conn = url.openConnection();
  10. Map headers = conn.getHeaderFields();
  11. Set<String> keys = headers.keySet();
  12. for( String key : keys ){
  13. String val = conn.getHeaderField(key);
  14. System.out.println(key+" "+val);
  15. }
  16. System.out.println( conn.getLastModified() );
  17. }
  18. }

以上代码运行输出结果为:

  1. Accept-Ranges bytes
  2. null HTTP/1.1 200 OK
  3. Server bfe/1.0.8.18
  4. Etag "588604c8-94d"
  5. Cache-Control private, no-cache, no-store, proxy-revalidate, no-transform
  6. Connection Keep-Alive
  7. Set-Cookie BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
  8. Pragma no-cache
  9. Last-Modified Mon, 23 Jan 2017 13:27:36 GMT
  10. Content-Length 2381
  11. Date Mon, 23 Sep 2019 05:36:41 GMT
  12. Content-Type text/html