Java如何獲取URL連線的日期?

2019-10-16 22:28:04

在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("https://www.tw511.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