In this example we will show how to get HTTP Response Header in Java.
Source Code
package com.beginner.examples;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;
public class GetHttpHeader {
public static void main(String[] args) {
try {
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection();
Map headers = conn.getHeaderFields();
Set keys = headers.keySet();
for(String key : keys) {
String value =conn.getHeaderField(key);
System.out.println(key+ " "+value);
}
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
}
Output:
Accept-Ranges bytes
null HTTP/1.1 200 OK
Server bfe/1.0.8.18
Etag "58860504-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:28:36 GMT
Content-Length 2381
Date Wed, 03 Apr 2019 08:41:47 GMT
Content-Type text/html
References
Imported packages in Java documentation: