一、基本方法获取HTTP头部信息
通过HTTP服务器响应信息时候,一般来说,HTTP首部可能包含所请求的文档的内容类型、文档长度(字节数)、对内容编码所采用的字符集、日期时间、内容的过期时间及内容的最后修改日期。可以使用URL API创建连接,获取相关信息,报头信息如下所示:
可以获取的信息类型如下所示:
代码如下:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class HeaderViewer {
public static void main(String[] args) {
try {
URL u = new URL("http://www.baidu.com");
URLConnection uc = u.openConnection();
System.out.println("Content-type: " + uc.getContentType());
if(uc.getContentEncoding() != null) {
System.out.println("Content-encoding: " + uc.getContentEncoding());
}
if (uc.getDate() != 0) {
System.out.println("Date: " + new Date(uc.getDate()));
}
if (uc.getLastModified() != 0) {
System.out.println("Last Modified: "
+ new Date(uc.getLastModified()));
}
if (uc.getExpiration() != 0) {
System.out.println("Expiration Date: "
+ uc.getExpiration());
}
if (uc.getContentLength() != 0) {
System.out.println("Content-length: "
+ uc.getContentLength());
}
} catch (MalformedURLException e) {
// TODO: handle exception
System.err.println(e);
} catch (IOException ex) {
// TODO: handle exception
System.err.println(ex);
}
}
}
运行结果图:
二、使用HeadName获取HTPP头部信息
如果想获取任意首部的字段,可以使用getHeaderField(String name)方法,而且不区分大小写:
public static void getHeadByName(URL url) {
try {
/**
* 不区分大小写
*/
URLConnection uc = url.openConnection();
System.out.println("Content-Type: "
+ uc.getHeaderField("content-type"));
System.out.println("CONTENT-TYPE: "
+ uc.getHeaderField("CONTENT-TYPE"));
} catch (MalformedURLException e) {
// TODO: handle exception
System.err.println(e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
二、使用HeadName获取HTPP头部信息
如果想获取所有首部的字段,可以使用getHeaderField(int n)方法,将所有头部信息输出:
/**
* 获取HTPP首部字段,通过ID的形式
* @param url
*/
public static void getHeaderbyID(URL url) {
try {
URLConnection uc = url.openConnection();
for (int i = 1; ; i++) {
String header = uc.getHeaderField(i);
if (header == null) {
break;
}
System.out.println(uc.getHeaderFieldKey(i) + ": "
+ header);
}
} catch (MalformedURLException e) {
// TODO: handle exception
System.err.println(e);
} catch (IOException e) {
// TODO: handle exception
System.err.println(e);
}
}
使用上面三种结果方式的截图: