有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 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. # 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 (  ) ;
    

    (未经测试!)