java如何检查网站是否已更新并发送电子邮件? 8 月,2 周 Questions & Answers 2691 嗨,我知道在Firefox上有一个网站检查器扩展,可以通过Firefox通知网站是否已更新 有没有代码片段可以实现相同的功能?我想用电子邮件通知网站更新
# 1 楼答案 这样做的目的是为页面内容持久化最后一个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()); } }
# 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 ( ) ; (未经测试!)
# 1 楼答案
这样做的目的是为页面内容持久化最后一个sha2哈希,并每5秒将当前哈希与持久化的哈希进行比较。顺便说一句,exmaple依赖apache编解码器库来执行sha2操作
# 2 楼答案
通过在URL对象上调用
openConnection()
来使用HttpUrlConnection
getResponseCode()
一旦从连接中读取,就会给你HTTP响应例如
(未经测试!)