在Java编程中,如何获取URL连接的日期?
以下示例演示如何使用HttpURLConnection
类的httpCon.getDate()
方法获取URL连接的日期。
package com.yiibai;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
public class URLConnectionDate {
public static void main(String args[]) throws Exception {
URL url = new URL("http://www.yiibai.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
long date = httpCon.getDate();
if (date == 0) {
System.out.println("No date information.");
} else {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss ");
System.out.println("It is now : " + formatter.format(new Date(date)));
}
}
}
上述代码示例将产生以下结果 -
It is now : 2017/09/20 21:33:26