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


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

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

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

  1. Transfer-Encoding chunked
  2. null HTTP/1.1 200 OK
  3. Server Tengine/1.3.0
  4. Connection keep-alive
  5. Vary Cookie
  6. Date Mon, 04 May 2015 03:54:05 GMT
  7. X-Pingback http://www.shouce.ren/xmlrpc.php
  8. X-Powered-By PHP/5.3.15
  9. Content-Type text/html; charset=UTF-8