Java 实例 - 获取 URL 响应头信息
以下实例演示了如何获取指定 URL 的响应头信息:
Main.java 文件
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) throws IOException{
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection();
Map headers = conn.getHeaderFields();
Set<String> keys = headers.keySet();
for( String key : keys ){
String val = conn.getHeaderField(key);
System.out.println(key+" "+val);
}
System.out.println( conn.getLastModified() );
}
}
以上代码运行输出结果为:
- Accept-Ranges bytes
- null HTTP/1.1 200 OK
- Server bfe/1.0.8.18
- Etag "588604c8-94d"
- Cache-Control private, no-cache, no-store, proxy-revalidate, no-transform
- Connection Keep-Alive
- Set-Cookie BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
- Pragma no-cache
- Last-Modified Mon, 23 Jan 2017 13:27:36 GMT
- Content-Length 2381
- Date Mon, 23 Sep 2019 05:36:41 GMT
- Content-Type text/html