微信公众号开发(八):文本处理器之历史上的今天

来源:互联网 发布:mysql数据库入门教程 编辑:程序博客网 时间:2024/05/03 16:32
主要练习JSoup的使用,解析HTML
/**
 * 历史上的今天处理器
 * @author 熊诗言
 *
 */
public class TodayInHisTextHandler extends DefaultMessageHandler {

    @Override
    public boolean canDo(Map<String, String> requestMap) {
        String content = requestMap.get("Content").trim();
        String msgType = requestMap.get("MsgType");
        return MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType) && "历史上的今天".equals(content);
    }

    @Override
    public BaseMessage handleByMe(Map<String, String> requestMap) {
        return MessageFactory.createTextMessage(fromUserName, toUserName, TodayInHistoryService.getTodayInHistoryInfo());
    }

}


/**
* 历史上的今天查询服务
*主要练习html的解析,找到html中特定的node
* @author 熊诗言
* @date 2015-09-05
*
*/
public class TodayInHistoryService {

    private static Logger logger = LoggerFactory.getLogger(TodayInHistoryService.class);
    /**
    * 发起http get 请求获取网页源代码
    *
    * @param requestUrl
    * @return
    */
    private static String httpRequest(String requestUrl) {
        StringBuffer buffer = null;
    
        try {
            // 建立连接
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
        
            // 获取输入流
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    
            // 读取返回结果
            buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
    
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
    * 从html 中抽取出历史上的今天信息
    *
    * @param html
    * @return
    */
    private static String extract(String html) {
        StringBuffer buffer = null;
        // 日期标签:区分是昨天还是今天
        String dateTag = getMonthDay(0);
        
        Pattern p = Pattern.compile("(.*)(<div class=\"listren\">)(.*?)(</div>)(.*)");
        Matcher m = p.matcher(html);
        if (m.matches()) {
            buffer = new StringBuffer();
            if (m.group(3).contains(getMonthDay(-1)))
                dateTag = getMonthDay(-1);
    
            // 拼装标题
            buffer.append("≡≡ ").append("历史上的").append(dateTag).append(" ≡≡").append("\n\n");
    
            int num = 0;
            // 抽取需要的数据
            for (String info : m.group(3).split(" ")) {
                if(num++<150){//最多5条否则字数超界,回复该公众号暂时无法提供服务
                    //TODO 明天继续把回复做得更人性化点儿
                    info = info.replace(dateTag, "").replace("(图)", "").replaceAll("</?[^>]+>", "").trim();
                    // 在每行末尾追加2 个换行符
                    if (!"".equals(info)) {
                        buffer.append(info).append("\n\n");
                    }
                }else {
                    break;
                }
            }
        }
        // 将buffer 最后两个换行符移除并返回
        return (null == buffer) ? null : buffer.toString();
    }

    /**
    * 获取前/后n 天日期(M 月d 日)
    *
    * @return
    */
    private static String getMonthDay(int diff) {
        DateFormat df = new SimpleDateFormat("M 月d 日");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, diff);
        return df.format(c.getTime());
    }
    /**
    * 从html 中抽取出历史上的今天信息
    *
    * @param html
    * @return
    */
    private static String extractByJsoup(String html) {
        Document document = Jsoup.parse(html);//其实也可以直接给URL或者文件
        /*Document document = null;
        try {
            document = Jsoup.parse(new File("C:\\Users\\xsy\\Desktop\\s.html"), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        Element element = document.select("div.listren").first();
        //System.out.println(element);
        Elements lis = element.child(0).children();//div->ul->lis
        
        // 日期标签:区分是昨天还是今天
        String dateTag = getMonthDay(0);
        
        StringBuffer buffer = new StringBuffer();
        // 拼装标题
        buffer.append("≡≡ ").append("历史上的").append(dateTag).append(" ≡≡").append("\n\n");
        int i=1;
        for (Element li : lis) {
            Element a = li.child(0);//->a
            buffer.append((i++)+":"+a.text()).append("\n");
        }
        
        return buffer.toString();
    }
    /**
    * 封装历史上的今天查询方法,供外部调用
    *
    * @return
    */
    public static String getTodayInHistoryInfo() {
        // 获取网页源代码
        String html = httpRequest("http://www.rijiben.com/");
        //System.out.println(html);
        // 从网页中抽取信息
        //String result = extract(html);
        
        String result = extractByJsoup(html);
        
        
        return result;
    }
    
    

    /**
    * 通过main 在本地测试
    *
    * @param args
    */
    public static void main(String[] args) {
        String info = getTodayInHistoryInfo();
        System.out.println(info);
    }
}
0 0
原创粉丝点击