如何检查网站是否已更新并发送电子邮件?

时间:2011-07-30 04:14:15

标签: java

您好我知道在Firefox上有一个网站检查器扩展程序,它将通过Firefox通知网站是否已更新。

是否有任何代码片段用于执行相同的功能?我希望收到有关网站更新的电子邮件通知。

2 个答案:

答案 0 :(得分:2)

这样可以保留页面内容的最后一个sha2哈希值,并且每5秒将当前哈希值与持久哈希值进行比较。顺便说一句,exmaple依赖于apache编解码器库来进行sha2操作。

import org.apache.commons.codec.digest.*;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * User: jhe
 */
public class UrlUpdatedChecker {

    static Map<String, String> checkSumDB = new HashMap<String, String>();

    public static void main(String[] args) throws IOException, InterruptedException {

        while (true) {
            String url = "http://www.stackoverflow.com";

            // query last checksum from map
            String lastChecksum = checkSumDB.get(url);

            // get current checksum using static utility method
            String currentChecksum = getChecksumForURL(url);

            if (currentChecksum.equals(lastChecksum)) {
                System.out.println("it haven't been updated");
            } else {
                // persist this checksum to map
                checkSumDB.put(url, currentChecksum);
                System.out.println("something in the content have changed...");

                // send email you can check: http://www.javacommerce.com/displaypage.jsp?name=javamail.sql&id=18274
            }

            Thread.sleep(5000);
        }
    }

    private static String getChecksumForURL(String spec) throws IOException {
        URL u = new URL(spec);
        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
        huc.setRequestMethod("GET");
        huc.setDoOutput(true);
        huc.connect();
        return DigestUtils.sha256Hex(huc.getInputStream()); 
    }
}

答案 1 :(得分:0)

通过在您的网址对象上调用HttpUrlConnection来使用openConnection()

从连接中读取后,

getResponseCode()将为您提供HTTP响应。

e.g。

   URL u = new URL ( "http://www.example.com/" ); 
   HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection (); 
   huc.setRequestMethod ("GET"); 
   huc.connect () ; 
   OutputStream os = huc.getOutputStream (  ) ; 
   int code = huc.getResponseCode (  ) ;

(未经测试!)