码迷,mamicode.com
首页 > 编程语言 > 详细

Java页面静态化工具类.java

时间:2014-12-21 17:49:49      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

package com.qq.utils;

import java.io.File;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

/**
 * HTML页面静态化工具
 * @author LiuJunGuang
 * @date 2014年2月22日上午11:46:42
 */
public class HtmlGeneratorUtils {
    private static Logger log = Logger.getLogger(HtmlGeneratorUtils.class);
    private static final String encoding = "UTF-8";

    /** 根据模版及参数产生静态页面 */
    public static boolean createHtmlPage(String url, String htmlFileName) {
        GetMethod getMethod = null;
        try {
            HttpClient httpClient = new HttpClient();
            httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
            getMethod = new GetMethod(url);
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());// 使用系统提供的默认的恢复策略,在发生异常时候将自动重试3次
            getMethod.addRequestHeader("Content-Type", "text/html;charset=UTF-8");// 设置Get方法提交参数时使用的字符集,以支持中文参数的正常传递
            int statusCode = httpClient.executeMethod(getMethod);// 执行Get方法并取得返回状态码,200表示正常,其它代码为异常
            if (statusCode != 200) {
                log.error("静态页面引擎在解析" + url + "产生静态页面" + htmlFileName + "时出错!");
            } else {
                IOUtils.copy(getMethod.getResponseBodyAsStream(), FileUtils.openOutputStream(new File(htmlFileName)));
            }
            return true;
        } catch (Exception ex) {
            log.error("静态页面引擎在解析" + url + "产生静态页面" + htmlFileName + "时出错:" + ex.getMessage(), ex);
        } finally {
            if (getMethod != null)
                getMethod.releaseConnection();
        }
        return false;
    }

    // 测试方法
    public static void main(String[] args) {
        HtmlGeneratorUtils.createHtmlPage("http://localhost:8080/MSDCP/index.action", "c:/a/a.html");
    }
}

 

Java页面静态化工具类.java

标签:

原文地址:http://www.cnblogs.com/studies/p/4176740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!