【问题标题】:How to check whether a website has been updated and send a email?如何检查网站是否已更新并发送电子邮件?
【发布时间】:2013-12-08 02:09:21
【问题描述】:

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

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

【问题讨论】:

  • 检查网站是否更新是什么意思?请提供更多详细信息。
  • 如果有 RSS 提要,您可以使用它...

标签: java


【解决方案1】:

这会持久化页面内容的最后一个 sha2 哈希值,并每 5 秒将当前哈希值与持久化的哈希值进行比较。顺便说一下,示例依赖 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()); 
    }
}

【讨论】:

    【解决方案2】:

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

    getResponseCode() 将在您从连接中读取数据后为您提供 HTTP 响应。

    例如

       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 (  ) ;
    

    (未测试!)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 2011-09-22
      • 2011-11-24
      • 1970-01-01
      • 2014-10-11
      • 2012-08-29
      • 1970-01-01
      相关资源
      最近更新 更多