使用java将网页保存为mht格式(转)

  1. package com.tag;   
  2.   
  3.   
  4.   
  5. import java.io.BufferedInputStream;   
  6.   
  7. import java.io.BufferedOutputStream;   
  8.   
  9. import java.io.BufferedReader;   
  10.   
  11. import java.io.ByteArrayInputStream;   
  12.   
  13. import java.io.DataOutputStream;   
  14.   
  15. import java.io.File;   
  16.   
  17. import java.io.FileInputStream;   
  18.   
  19. import java.io.FileOutputStream;   
  20.   
  21. import java.io.FileWriter;   
  22.   
  23. import java.io.IOException;   
  24.   
  25. import java.io.InputStream;   
  26.   
  27. import java.io.InputStreamReader;   
  28.   
  29. import java.io.OutputStream;   
  30.   
  31. import java.io.Reader;   
  32.   
  33. import java.net.MalformedURLException;   
  34.   
  35. import java.net.URL;   
  36.   
  37. import java.util.*;   
  38.   
  39.   
  40.   
  41. import org.htmlparser.Parser;   
  42.   
  43. import org.htmlparser.Tag;   
  44.   
  45. import org.htmlparser.filters.TagNameFilter;   
  46.   
  47. import org.htmlparser.lexer.Lexer;   
  48.   
  49. import org.htmlparser.lexer.Page;   
  50.   
  51. import org.htmlparser.util.DefaultParserFeedback;   
  52.   
  53. import org.htmlparser.util.NodeList;   
  54.   
  55. import org.htmlparser.util.ParserException;   
  56.   
  57.   
  58.   
  59. import toptrack.tools.JQuery;   
  60.   
  61.   
  62.   
  63. import javax.activation.DataHandler;   
  64.   
  65. import javax.activation.DataSource;   
  66.   
  67. import javax.activation.MimetypesFileTypeMap;   
  68.   
  69. import javax.mail.Message;   
  70.   
  71. import javax.mail.MessagingException;   
  72.   
  73. import javax.mail.Multipart;   
  74.   
  75. import javax.mail.Session;   
  76.   
  77. import javax.mail.internet.InternetAddress;   
  78.   
  79. import javax.mail.internet.MimeBodyPart;   
  80.   
  81. import javax.mail.internet.MimeMessage;   
  82.   
  83. import javax.mail.internet.MimeMultipart;   
  84.   
  85. import javax.mail.internet.MimePartDataSource;   
  86.   
  87.   
  88.   
  89. /**  
  90.  
  91.  * mht文件解析类  
  92.  
  93.  * @author dl  
  94.  
  95.  */  
  96.   
  97. public class Html2MHTCompiler {   
  98.   
  99.     private URL strWeb = null/**网页地址*/  
  100.   
  101.     private String strText = null/**网页文本内容*/  
  102.   
  103.     private String strFileName = null/**本地文件名*/  
  104.   
  105.     private String strEncoding = null/**网页编码*/  
  106.   
  107.        
  108.   
  109.     //mht格式附加信息   
  110.   
  111.     private String from = "dongle2001@126.com";   
  112.   
  113.     private String to;   
  114.   
  115.     private String subject = "mht compile";   
  116.   
  117.     private String cc;   
  118.   
  119.     private String bcc;   
  120.   
  121.     private String smtp = "localhost";   
  122.   
  123.        
  124.   
  125.     public static void main(String[] args) {   
  126.   
  127.         String strUrl = "http://www.mtime.com/my/tropicofcancer/blog/843555/";   
  128.   
  129.         String strEncoding = "utf-8";   
  130.   
  131.         String strText = JQuery.getHtmlText(strUrl, strEncoding, null);   
  132.   
  133.         if (strText == null)   
  134.   
  135.             return;   
  136.   
  137.         Html2MHTCompiler h2t = new Html2MHTCompiler(strText, strUrl, strEncoding, "test.mht");   
  138.   
  139.         h2t.compile();   
  140.   
  141.         //Html2MHTCompiler.mht2html("test.mht", "a.html");   
  142.   
  143.     }   
  144.   
  145.        
  146.   
  147.     /**  
  148.  
  149.      *<br>方法说明:初始化  
  150.  
  151.      *<br>输入参数:strText 网页文本内容; strUrl 网页地址; strEncoding 网页编码; strFileName 本地文件名  
  152.  
  153.      *<br>返回类型:  
  154.  
  155.      */  
  156.   
  157.     public Html2MHTCompiler(String strText, String strUrl, String strEncoding, String strFileName) {   
  158.   
  159.         // TODO Auto-generated constructor stub   
  160.   
  161.         try {   
  162.   
  163.             strWeb = new URL(strUrl);   
  164.   
  165.         } catch (MalformedURLException e) {   
  166.   
  167.             // TODO Auto-generated catch block   
  168.   
  169.             e.printStackTrace();   
  170.   
  171.             return;   
  172.   
  173.         }   
  174.   
  175.            
  176.   
  177.         this.strText = strText;   
  178.   
  179.         this.strEncoding = strEncoding;   
  180.   
  181.         this.strFileName = strFileName;   
  182.   
  183.     }   
  184.   
  185.   
  186.   
  187.     /**  
  188.  
  189.      *<br>方法说明:执行下载操作  
  190.  
  191.      *<br>输入参数:  
  192.  
  193.      *<br>返回类型:  
  194.  
  195.      */  
  196.   
  197.     public boolean compile() {   
  198.   
  199.         if (strWeb == null || strText == null || strFileName == null || strEncoding == null)   
  200.   
  201.             return false;   
  202.   
  203.         HashMap urlMap = new HashMap();   
  204.   
  205.         NodeList nodes = new NodeList();   
  206.   
  207.         try {   
  208.   
  209.             Parser parser = createParser(strText);   
  210.   
  211.             parser.setEncoding(strEncoding);   
  212.   
  213.             nodes = parser.parse(null);   
  214.   
  215.         } catch (ParserException e) {   
  216.   
  217.             // TODO Auto-generated catch block   
  218.   
  219.             e.printStackTrace();   
  220.   
  221.         }   
  222.   
  223.         extractAllScriptNodes(nodes);   
  224.   
  225.         ArrayList urlScriptList = extractAllScriptNodes(nodes, urlMap);   
  226.   
  227.         ArrayList urlImageList = extractAllImageNodes(nodes, urlMap);   
  228.   
  229.         for (Iterator iter = urlMap.entrySet().iterator(); iter.hasNext();) {   
  230.   
  231.             Map.Entry entry = (Map.Entry) iter.next();   
  232.   
  233.             String key = (String)entry.getKey();   
  234.   
  235.             String val = (String)entry.getValue();   
  236.   
  237.             strText = JHtmlClear.replace(strText, val, key);   
  238.   
  239.         }   
  240.   
  241.         try {   
  242.   
  243.             createMhtArchive(strText, urlScriptList, urlImageList);   
  244.   
  245.         } catch (Exception e) {   
  246.   
  247.             // TODO Auto-generated catch block   
  248.   
  249.             e.printStackTrace();   
  250.   
  251.             return false;   
  252.   
  253.         }   
  254.   
  255.         return true;   
  256.   
  257.     }   
  258.   
  259.        
  260.   
  261.     /**  
  262.  
  263.      *<br>方法说明:建立HTML parser  
  264.  
  265.      *<br>输入参数:inputHTML 网页文本内容  
  266.  
  267.      *<br>返回类型:HTML parser  
  268.  
  269.      */  
  270.   
  271.     private Parser createParser(String inputHTML) {   
  272.   
  273.         // TODO Auto-generated method stub   
  274.   
  275.         Lexer mLexer = new Lexer(new Page(inputHTML));   
  276.   
  277.         return new Parser(mLexer, new DefaultParserFeedback(DefaultParserFeedback.QUIET));    
  278.   
  279.     }   
  280.   
  281.   
  282.   
  283.     /**  
  284.  
  285.      *<br>方法说明:抽取基础URL地址  
  286.  
  287.      *<br>输入参数:nodes 网页标签集合  
  288.  
  289.      *<br>返回类型:  
  290.  
  291.      */  
  292.   
  293.     private void extractAllScriptNodes(NodeList nodes) {   
  294.   
  295.         NodeList filtered = nodes.extractAllNodesThatMatch(new TagNameFilter(   
  296.   
  297.                 "BASE"), true);   
  298.   
  299.         if (filtered != null && filtered.size() > 0) {   
  300.   
  301.             Tag tag = (Tag) filtered.elementAt(0);   
  302.   
  303.             String href = tag.getAttribute("href");   
  304.   
  305.             if (href != null && href.length() > 0) {   
  306.   
  307.                 try {   
  308.   
  309.                     strWeb = new URL(href);   
  310.   
  311.                 } catch (MalformedURLException e) {   
  312.   
  313.                     // TODO Auto-generated catch block   
  314.   
  315.                     e.printStackTrace();   
  316.   
  317.                 }   
  318.   
  319.             }   
  320.   
  321.         }   
  322.   
  323.     }   
  324.   
  325.   
  326.   
  327.     /**  
  328.  
  329.      *<br>方法说明:抽取网页包含的css,js链接  
  330.  
  331.      *<br>输入参数:nodes 网页标签集合; urlMap 已存在的url集合  
  332.  
  333.      *<br>返回类型:css,js链接的集合  
  334.  
  335.      */  
  336.   
  337.     private ArrayList extractAllScriptNodes(NodeList nodes, HashMap urlMap) {   
  338.   
  339.         ArrayList urlList = new ArrayList();   
  340.   
  341.         NodeList filtered = nodes.extractAllNodesThatMatch(new TagNameFilter("script"), true);   
  342.   
  343.         for (int i = 0; i < filtered.size(); i++) {   
  344.   
  345.             Tag tag = (Tag) filtered.elementAt(i);   
  346.   
  347.             String src = tag.getAttribute("src");   
  348.   
  349.             // Handle external css file's url   
  350.   
  351.             if (src != null && src.length() > 0) {   
  352.   
  353.                 String innerURL = src;   
  354.   
  355.                 String absoluteURL = makeAbsoluteURL(strWeb, innerURL);   
  356.   
  357.                 if (absoluteURL != null && !urlMap.containsKey(absoluteURL)) {   
  358.   
  359.                     urlMap.put(absoluteURL, innerURL);   
  360.   
  361.                     ArrayList urlInfo = new ArrayList();   
  362.   
  363.                     urlInfo.add(innerURL);   
  364.   
  365.                     urlInfo.add(absoluteURL);   
  366.   
  367.                     urlList.add(urlInfo);   
  368.   
  369.                 }   
  370.   
  371.                 tag.setAttribute("src", absoluteURL);                      
  372.   
  373.             }   
  374.   
  375.         }   
  376.   
  377.            
  378.   
  379.         filtered = nodes.extractAllNodesThatMatch(new TagNameFilter("link"), true);   
  380.   
  381.         for (int i = 0; i < filtered.size(); i++) {   
  382.   
  383.             Tag tag = (Tag) filtered.elementAt(i);   
  384.   
  385.             String type = (tag.getAttribute("type"));   
  386.   
  387.             String rel = (tag.getAttribute("rel"));   
  388.   
  389.             String href = tag.getAttribute("href");   
  390.   
  391.   
  392.   
  393.             boolean isCssFile = false;   
  394.   
  395.             if (rel != null) {   
  396.   
  397.                 isCssFile = rel.indexOf("stylesheet") != -1;   
  398.   
  399.             } else if (type != null) {   
  400.   
  401.                 isCssFile |= type.indexOf("text/css") != -1;   
  402.   
  403.             }   
  404.   
  405.             // Handle external css file's url   
  406.   
  407.             if (isCssFile && href != null && href.length() > 0) {   
  408.   
  409.                 String innerURL = href;   
  410.   
  411.                 String absoluteURL = makeAbsoluteURL(strWeb, innerURL);   
  412.   
  413.                 if (absoluteURL != null && !urlMap.containsKey(absoluteURL)) {   
  414.   
  415.                     urlMap.put(absoluteURL, innerURL);   
  416.   
  417.                     ArrayList urlInfo = new ArrayList();   
  418.   
  419.                     urlInfo.add(innerURL);   
  420.   
  421.                     urlInfo.add(absoluteURL);   
  422.   
  423.                     urlList.add(urlInfo);   
  424.   
  425.                 }   
  426.   
  427.                 tag.setAttribute("href", absoluteURL);   
  428.   
  429.             }   
  430.   
  431.         }   
  432.   
  433.            
  434.   
  435.         return urlList;   
  436.   
  437.     }   
  438.   
  439.        
  440.   
  441.     /**  
  442.  
  443.      *<br>方法说明:抽取网页包含的图像链接  
  444.  
  445.      *<br>输入参数:nodes 网页标签集合; urlMap 已存在的url集合  
  446.  
  447.      *<br>返回类型:图像链接集合  
  448.  
  449.      */  
  450.   
  451.     private ArrayList extractAllImageNodes(NodeList nodes, HashMap urlMap) {   
  452.   
  453.         ArrayList urlList = new ArrayList();   
  454.   
  455.         NodeList filtered = nodes.extractAllNodesThatMatch(new TagNameFilter("IMG"), true);   
  456.   
  457.         for (int i = 0; i < filtered.size(); i++) {   
  458.   
  459.             Tag tag = (Tag) filtered.elementAt(i);   
  460.   
  461.             String src = tag.getAttribute("src");   
  462.   
  463.             // Handle external css file's url   
  464.   
  465.             if (src != null && src.length() > 0) {   
  466.   
  467.                 String innerURL = src;   
  468.   
  469.                 String absoluteURL = makeAbsoluteURL(strWeb, innerURL);   
  470.   
  471.                 if (absoluteURL != null && !urlMap.containsKey(absoluteURL)) {   
  472.   
  473.                     urlMap.put(absoluteURL, innerURL);   
  474.   
  475.                     ArrayList urlInfo = new ArrayList();   
  476.   
  477.                     urlInfo.add(innerURL);   
  478.   
  479.                     urlInfo.add(absoluteURL);   
  480.   
  481.                     urlList.add(urlInfo);   
  482.   
  483.                 }   
  484.   
  485.                 tag.setAttribute("src", absoluteURL);                      
  486.   
  487.             }   
  488.   
  489.         }   
  490.   
  491.            
  492.   
  493.         return urlList;   
  494.   
  495.     }   
  496.   
  497.   
  498.   
  499.     /**  
  500.  
  501.      *<br>方法说明:相对路径转绝对路径  
  502.  
  503.      *<br>输入参数:strWeb 网页地址; innerURL 相对路径链接  
  504.  
  505.      *<br>返回类型:绝对路径链接  
  506.  
  507.      */  
  508.   
  509.     public static String makeAbsoluteURL(URL strWeb, String innerURL) {   
  510.   
  511.         // TODO Auto-generated method stub   
  512.   
  513.         //去除后缀   
  514.   
  515.         int pos = innerURL.indexOf("?");   
  516.   
  517.         if (pos != -1) {   
  518.   
  519.             innerURL = innerURL.substring(0, pos);   
  520.   
  521.         }   
  522.   
  523.         if (innerURL != null  
  524.   
  525.                 && innerURL.toLowerCase().indexOf("http") == 0) {   
  526.   
  527.             System.out.println(innerURL);   
  528.   
  529.             return innerURL;   
  530.   
  531.         }   
  532.   
  533.            
  534.   
  535.         URL linkUri = null;   
  536.   
  537.         try {   
  538.   
  539.             linkUri = new URL(strWeb, innerURL);   
  540.   
  541.         } catch (MalformedURLException e) {   
  542.   
  543.             //TODO Auto-generated catch block   
  544.   
  545.             e.printStackTrace();   
  546.   
  547.             return null;   
  548.   
  549.         }   
  550.   
  551.            
  552.   
  553.         String absURL = linkUri.toString();   
  554.   
  555.         absURL = JHtmlClear.replace(absURL, "../""");   
  556.   
  557.         absURL = JHtmlClear.replace(absURL, "./""");   
  558.   
  559.         System.out.println(absURL);   
  560.   
  561.         return absURL;   
  562.   
  563.     }   
  564.   
  565.   
  566.   
  567.     /**  
  568.  
  569.      *<br>方法说明:创建mht文件  
  570.  
  571.      *<br>输入参数:content 网页文本内容; urlScriptList 脚本链接集合; urlImageList 图片链接集合  
  572.  
  573.      *<br>返回类型:  
  574.  
  575.      */  
  576.   
  577.     private void createMhtArchive(String content, ArrayList urlScriptList, ArrayList urlImageList) throws Exception {   
  578.   
  579.         //Instantiate a Multipart object   
  580.   
  581.         MimeMultipart mp = new MimeMultipart("related");   
  582.   
  583.         Properties props = new Properties();   
  584.   
  585.         props.put("mail.smtp.host", smtp);   
  586.   
  587.         Session session = Session.getDefaultInstance(props, null);   
  588.   
  589.         MimeMessage msg = new MimeMessage(session);   
  590.   
  591.         // set mailer   
  592.   
  593.         msg.setHeader("X-Mailer""Code Manager .SWT");   
  594.   
  595.   
  596.   
  597.         // set from   
  598.   
  599.         if (from != null) {   
  600.   
  601.             msg.setFrom(new InternetAddress(from));   
  602.   
  603.         }   
  604.   
  605.         // set subject   
  606.   
  607.         if (subject != null) {   
  608.   
  609.             msg.setSubject(subject);   
  610.   
  611.         }   
  612.   
  613.         // to   
  614.   
  615.         if (to != null) {   
  616.   
  617.             InternetAddress[] toAddresses = getInetAddresses(to);   
  618.   
  619.             msg.setRecipients(Message.RecipientType.TO, toAddresses);   
  620.   
  621.         }   
  622.   
  623.         // cc   
  624.   
  625.         if (cc != null) {   
  626.   
  627.             InternetAddress[] ccAddresses = getInetAddresses(cc);   
  628.   
  629.             msg.setRecipients(Message.RecipientType.CC, ccAddresses);   
  630.   
  631.         }   
  632.   
  633.         // bcc   
  634.   
  635.         if (bcc != null) {   
  636.   
  637.             InternetAddress[] bccAddresses = getInetAddresses(bcc);   
  638.   
  639.             msg.setRecipients(Message.RecipientType.BCC, bccAddresses);   
  640.   
  641.         }   
  642.   
  643.            
  644.   
  645.         //设置网页正文   
  646.   
  647.         MimeBodyPart bp = new MimeBodyPart();   
  648.   
  649.         bp.setText(content, strEncoding);   
  650.   
  651.         bp.addHeader("Content-Type""text/html;charset=" + strEncoding);   
  652.   
  653.         bp.addHeader("Content-Location", strWeb.toString());   
  654.   
  655.         mp.addBodyPart(bp);   
  656.   
  657.         int urlCount = urlScriptList.size();   
  658.   
  659.         for (int i = 0; i < urlCount; i++) {   
  660.   
  661.             bp = new MimeBodyPart();   
  662.   
  663.             ArrayList urlInfo = (ArrayList) urlScriptList.get(i);   
  664.   
  665.             // String url = urlInfo.get(0).toString();   
  666.   
  667.             String absoluteURL = urlInfo.get(1).toString();   
  668.   
  669.             bp   
  670.   
  671.             .addHeader("Content-Location",   
  672.   
  673.                     javax.mail.internet.MimeUtility   
  674.   
  675.                             .encodeWord(java.net.URLDecoder   
  676.   
  677.                                     .decode(absoluteURL, strEncoding)));   
  678.   
  679.             DataSource source = new AttachmentDataSource(absoluteURL, "text");   
  680.   
  681.             bp.setDataHandler(new DataHandler(source));   
  682.   
  683.             mp.addBodyPart(bp);   
  684.   
  685.         }   
  686.   
  687.            
  688.   
  689.         urlCount = urlImageList.size();   
  690.   
  691.         for (int i = 0; i < urlCount; i++) {   
  692.   
  693.             bp = new MimeBodyPart();   
  694.   
  695.             ArrayList urlInfo = (ArrayList) urlImageList.get(i);   
  696.   
  697.             // String url = urlInfo.get(0).toString();   
  698.   
  699.             String absoluteURL = urlInfo.get(1).toString();   
  700.   
  701.             bp   
  702.   
  703.             .addHeader("Content-Location",   
  704.   
  705.                     javax.mail.internet.MimeUtility   
  706.   
  707.                             .encodeWord(java.net.URLDecoder   
  708.   
  709.                                     .decode(absoluteURL, strEncoding)));   
  710.   
  711.             DataSource source = new AttachmentDataSource(absoluteURL, "image");   
  712.   
  713.             bp.setDataHandler(new DataHandler(source));   
  714.   
  715.             mp.addBodyPart(bp);   
  716.   
  717.         }   
  718.   
  719.         msg.setContent(mp);   
  720.   
  721.         // write the mime multi part message to a file   
  722.   
  723.         msg.writeTo(new FileOutputStream(strFileName));   
  724.   
  725.     }   
  726.   
  727.        
  728.   
  729.     /**  
  730.  
  731.      *<br>方法说明:mht转html  
  732.  
  733.      *<br>输入参数:strMht mht文件路径; strHtml html文件路径  
  734.  
  735.      *<br>返回类型:  
  736.  
  737.      */  
  738.   
  739.     public static void mht2html(String strMht, String strHtml) {   
  740.   
  741.         try {   
  742.   
  743.             //TODO readEmlFile   
  744.   
  745.             InputStream fis = new FileInputStream(strMht);   
  746.   
  747.             Session mailSession = Session.getDefaultInstance(System.getProperties(), null);   
  748.   
  749.             MimeMessage msg = new MimeMessage(mailSession, fis);   
  750.   
  751.             Object content = msg.getContent();    
  752.   
  753.             if (content instanceof Multipart) {   
  754.   
  755.                 MimeMultipart mp = (MimeMultipart)content;   
  756.   
  757.                 MimeBodyPart bp1 = (MimeBodyPart)mp.getBodyPart(0);   
  758.   
  759.                 String strEncodng = getEncoding(bp1);   
  760.   
  761.                 String strText = getHtmlText(bp1, strEncodng);   
  762.   
  763.                 if (strText == null)   
  764.   
  765.                     return;   
  766.   
  767.                 File parent = null;   
  768.   
  769.                 if (mp.getCount() > 1) {   
  770.   
  771.                     parent = new File(new File(strHtml).getAbsolutePath() + ".files");   
  772.   
  773.                     parent.mkdirs();   
  774.   
  775.                     if (!parent.exists())   
  776.   
  777.                         return;   
  778.   
  779.                 }   
  780.   
  781.                 for (int i = 1; i < mp.getCount(); ++i) {   
  782.   
  783.                     MimeBodyPart bp = (MimeBodyPart)mp.getBodyPart(i);   
  784.   
  785.                        
  786.   
  787.                     String strUrl = getResourcesUrl(bp);   
  788.   
  789.                     if (strUrl == null)   
  790.   
  791.                         continue;   
  792.   
  793.                        
  794.   
  795.                     DataHandler dataHandler = bp.getDataHandler();   
  796.   
  797.                     MimePartDataSource source = (MimePartDataSource)dataHandler.getDataSource();   
  798.   
  799.                     File resources = new File(parent.getAbsolutePath() + File.separator + getName(strUrl, i));   
  800.   
  801.                     if (saveResourcesFile(resources, bp.getInputStream()))   
  802.   
  803.                         strText = JHtmlClear.replace(strText, strUrl, resources.getAbsolutePath());   
  804.   
  805.                 }   
  806.   
  807.                 saveHtml(strText, strHtml);   
  808.   
  809.             }   
  810.   
  811.         } catch (Exception e) {   
  812.   
  813.             // TODO Auto-generated catch block   
  814.   
  815.             e.printStackTrace();   
  816.   
  817.         }   
  818.   
  819.     }   
  820.   
  821.   
  822.   
  823.     /**  
  824.  
  825.      *<br>方法说明:得到资源文件的name  
  826.  
  827.      *<br>输入参数:strName 资源文件链接, ID 资源文件的序号  
  828.  
  829.      *<br>返回类型:资源文件的本地临时文件名  
  830.  
  831.      */  
  832.   
  833.     public static String getName(String strName, int ID) {   
  834.   
  835.         char separator = '/';   
  836.   
  837.         System.out.println(strName);   
  838.   
  839.         System.out.println(separator);   
  840.   
  841.         if( strName.lastIndexOf(separator) >= 0)   
  842.   
  843.              return format(strName.substring(strName.lastIndexOf(separator) + 1));   
  844.   
  845.          return "temp" + ID;   
  846.   
  847.     }   
  848.   
  849.        
  850.   
  851.     /**  
  852.  
  853.      *<br>方法说明:得到网页编码  
  854.  
  855.      *<br>输入参数:bp MimeBodyPart类型的网页内容  
  856.  
  857.      *<br>返回类型:MimeBodyPart里的网页内容的编码  
  858.  
  859.      */  
  860.   
  861.     private static String getEncoding(MimeBodyPart bp) {      
  862.   
  863.         if (bp != null) {      
  864.   
  865.             try {   
  866.   
  867.                 Enumeration list = bp.getAllHeaders();   
  868.   
  869.                 while (list.hasMoreElements()) {   
  870.   
  871.                     javax.mail.Header head = (javax.mail.Header)list.nextElement();   
  872.   
  873.                     if (head.getName().compareTo("Content-Type") == 0) {   
  874.   
  875.                         String strType = head.getValue();   
  876.   
  877.                         int pos = strType.indexOf("charset=");   
  878.   
  879.                         if (pos != -1) {   
  880.   
  881.                             String strEncoding = strType.substring(pos + 8, strType.length());   
  882.   
  883.                             if (strEncoding.toLowerCase().compareTo("gb2312") == 0) {   
  884.   
  885.                                 strEncoding = "gbk";   
  886.   
  887.                             }   
  888.   
  889.                             return strEncoding;   
  890.   
  891.                         }   
  892.   
  893.                     }   
  894.   
  895.                 }   
  896.   
  897.             } catch (MessagingException e) {   
  898.   
  899.                 // TODO Auto-generated catch block   
  900.   
  901.                 e.printStackTrace();   
  902.   
  903.             }   
  904.   
  905.   
  906.   
  907.         }      
  908.   
  909.         return null;      
  910.   
  911.     }   
  912.   
  913.        
  914.   
  915.     /**  
  916.  
  917.      *<br>方法说明:得到资源文件url  
  918.  
  919.      *<br>输入参数:bp MimeBodyPart类型的网页内容  
  920.  
  921.      *<br>返回类型:资源文件url  
  922.  
  923.      */  
  924.   
  925.     private static String getResourcesUrl(MimeBodyPart bp) {      
  926.   
  927.         if (bp != null) {      
  928.   
  929.             try {   
  930.   
  931.                 Enumeration list = bp.getAllHeaders();   
  932.   
  933.                 while (list.hasMoreElements()) {   
  934.   
  935.                     javax.mail.Header head = (javax.mail.Header)list.nextElement();   
  936.   
  937.                     if (head.getName().compareTo("Content-Location") == 0) {   
  938.   
  939.                         return head.getValue();   
  940.   
  941.                     }   
  942.   
  943.                 }   
  944.   
  945.             } catch (MessagingException e) {   
  946.   
  947.                 // TODO Auto-generated catch block   
  948.   
  949.                 e.printStackTrace();   
  950.   
  951.             }   
  952.   
  953.   
  954.   
  955.         }      
  956.   
  957.         return null;      
  958.   
  959.     }      
  960.   
  961.   
  962.   
  963.     /**  
  964.  
  965.      *<br>方法说明:格式化文件名  
  966.  
  967.      *<br>输入参数:strName 文件名  
  968.  
  969.      *<br>返回类型:经过处理的符合命名规则的文件名  
  970.  
  971.      */  
  972.   
  973.     private static String format(String strName) {   
  974.   
  975.         if (strName == null)   
  976.   
  977.             return null;   
  978.   
  979.         strName = strName.replaceAll("     "" ");   
  980.   
  981.         String strText = "///:*?/"<>|^___FCKpd___0quot;;   
  982.   
  983.         for (int i = 0; i < strName.length(); ++i) {   
  984.   
  985.             String ch = String.valueOf(strName.charAt(i));   
  986.   
  987.             if (strText.indexOf(ch) != -1) {   
  988.   
  989.                 strName = strName.replace(strName.charAt(i), '-');   
  990.   
  991.             }   
  992.   
  993.         }   
  994.   
  995.         return strName;   
  996.   
  997.     }   
  998.   
  999.        
  1000.   
  1001.     /**  
  1002.  
  1003.      *<br>方法说明:保存资源文件  
  1004.  
  1005.      *<br>输入参数:resources 要创建的资源文件; inputStream 要输入文件中的流  
  1006.  
  1007.      *<br>返回类型:boolean  
  1008.  
  1009.      */  
  1010.   
  1011.     private static boolean saveResourcesFile(File resources, InputStream inputStream) {   
  1012.   
  1013.         if (resources == null || inputStream == null) {   
  1014.   
  1015.             return false;    
  1016.   
  1017.         }   
  1018.   
  1019.         BufferedInputStream in = null;   
  1020.   
  1021.         FileOutputStream fio = null;   
  1022.   
  1023.         BufferedOutputStream osw = null;   
  1024.   
  1025.         try {   
  1026.   
  1027.             in = new BufferedInputStream(inputStream);   
  1028.   
  1029.             fio = new FileOutputStream(resources);   
  1030.   
  1031.             osw = new BufferedOutputStream(new DataOutputStream(fio));   
  1032.   
  1033.             int b;   
  1034.   
  1035.             byte[] a = new byte[1024];   
  1036.   
  1037.             boolean isEmpty = true;   
  1038.   
  1039.             while ((b = in.read(a)) != -1) {   
  1040.   
  1041.                 isEmpty = false;   
  1042.   
  1043.                 osw.write(a, 0, b);   
  1044.   
  1045.                 osw.flush();   
  1046.   
  1047.             }   
  1048.   
  1049.             osw.close();   
  1050.   
  1051.             fio.close();   
  1052.   
  1053.             in.close();   
  1054.   
  1055.             inputStream.close();   
  1056.   
  1057.             if (isEmpty)   
  1058.   
  1059.                 resources.delete();   
  1060.   
  1061.             return true;   
  1062.   
  1063.         } catch (Exception e) {   
  1064.   
  1065.             // TODO Auto-generated catch block   
  1066.   
  1067.             e.printStackTrace();   
  1068.   
  1069.             System.out.println("解析mht失败");   
  1070.   
  1071.             return false;   
  1072.   
  1073.         } finally{   
  1074.   
  1075.             try {   
  1076.   
  1077.                 if (osw != null)   
  1078.   
  1079.                     osw.close();   
  1080.   
  1081.                 if (fio != null)   
  1082.   
  1083.                     fio.close();   
  1084.   
  1085.                 if (in != null)   
  1086.   
  1087.                     in.close();   
  1088.   
  1089.                 if (inputStream != null)   
  1090.   
  1091.                     inputStream.close();   
  1092.   
  1093.             } catch (Exception e) {   
  1094.   
  1095.                 e.printStackTrace();   
  1096.   
  1097.                 System.out.println("解析mht失败");   
  1098.   
  1099.                 return false;   
  1100.   
  1101.             }      
  1102.   
  1103.         }   
  1104.   
  1105.     }   
  1106.   
  1107.        
  1108.   
  1109.     /**  
  1110.  
  1111.      *<br>方法说明:得到mht文件的标题  
  1112.  
  1113.      *<br>输入参数:mhtFilename mht文件名  
  1114.  
  1115.      *<br>返回类型:mht文件的标题  
  1116.  
  1117.      */  
  1118.   
  1119.     public static String getTitle(String mhtFilename) {   
  1120.   
  1121.         try {   
  1122.   
  1123.             //TODO readEmlFile   
  1124.   
  1125.             InputStream fis = new FileInputStream(mhtFilename);   
  1126.   
  1127.             Session mailSession = Session.getDefaultInstance(System.getProperties(), null);   
  1128.   
  1129.             MimeMessage msg = new MimeMessage(mailSession, fis);   
  1130.   
  1131.             Object content = msg.getContent();    
  1132.   
  1133.             if (content instanceof Multipart) {   
  1134.   
  1135.                 MimeMultipart mp = (MimeMultipart)content;   
  1136.   
  1137.                 MimeBodyPart bp1 = (MimeBodyPart)mp.getBodyPart(0);   
  1138.   
  1139.                 String strEncodng = getEncoding(bp1);   
  1140.   
  1141.                 String strText = getHtmlText(bp1, strEncodng);   
  1142.   
  1143.                 if (strText == null)   
  1144.   
  1145.                     return null;   
  1146.   
  1147.                 strText = strText.toLowerCase();   
  1148.   
  1149.                 int pos1 = strText.indexOf("<title>");   
  1150.   
  1151.                 int pos2 = strText.indexOf("</title>");   
  1152.   
  1153.                 if (pos1 != -1 && pos2!= -1 && pos2 > pos1) {   
  1154.   
  1155.                     return strText.substring(pos1 + 7, pos2).trim();   
  1156.   
  1157.                 }   
  1158.   
  1159.             }   
  1160.   
  1161.             return null;   
  1162.   
  1163.         } catch (Exception e) {   
  1164.   
  1165.             // TODO Auto-generated catch block   
  1166.   
  1167.             e.printStackTrace();   
  1168.   
  1169.             return null;   
  1170.   
  1171.         }   
  1172.   
  1173.     }   
  1174.   
  1175.   
  1176.   
  1177.     /**  
  1178.  
  1179.      *<br>方法说明:得到html文本  
  1180.  
  1181.      *<br>输入参数:bp MimeBodyPart类型的网页内容; strEncoding 内容编码  
  1182.  
  1183.      *<br>返回类型:html文本  
  1184.  
  1185.      */  
  1186.   
  1187.     private static String getHtmlText(MimeBodyPart bp, String strEncoding) {   
  1188.   
  1189.         InputStream textStream = null;   
  1190.   
  1191.         BufferedInputStream buff = null;   
  1192.   
  1193.         BufferedReader br = null;   
  1194.   
  1195.         Reader r = null;   
  1196.   
  1197.         try {   
  1198.   
  1199.             textStream = bp.getInputStream();   
  1200.   
  1201.             buff = new BufferedInputStream(textStream);   
  1202.   
  1203.             r = new InputStreamReader(buff, strEncoding);      
  1204.   
  1205.             br = new BufferedReader(r);   
  1206.   
  1207.             StringBuffer strHtml = new StringBuffer("");   
  1208.   
  1209.             String strLine = null;   
  1210.   
  1211.             while ((strLine = br.readLine()) != null) {   
  1212.   
  1213.                 strHtml.append(strLine + "/r/n");   
  1214.   
  1215.             }   
  1216.   
  1217.             br.close();   
  1218.   
  1219.             r.close();   
  1220.   
  1221.             textStream.close();   
  1222.   
  1223.             return strHtml.toString();   
  1224.   
  1225.         } catch (Exception e) {   
  1226.   
  1227.             // TODO Auto-generated catch block   
  1228.   
  1229.             e.printStackTrace();           
  1230.   
  1231.         } finally{         
  1232.   
  1233.             try{   
  1234.   
  1235.                 if (br != null)   
  1236.   
  1237.                     br.close();   
  1238.   
  1239.                 if (buff != null)   
  1240.   
  1241.                     buff.close();   
  1242.   
  1243.                 if (textStream != null)   
  1244.   
  1245.                     textStream.close();   
  1246.   
  1247.             }catch(Exception e){   
  1248.   
  1249.                 System.out.println("解析mht失败");   
  1250.   
  1251.             }   
  1252.   
  1253.         }   
  1254.   
  1255.         return null;   
  1256.   
  1257.     }   
  1258.   
  1259.   
  1260.   
  1261.     /**  
  1262.  
  1263.      *<br>方法说明:保存html文件  
  1264.  
  1265.      *<br>输入参数:strText html内容; strHtml html文件名  
  1266.  
  1267.      *<br>返回类型:  
  1268.  
  1269.      */  
  1270.   
  1271.     private static void saveHtml(String strText, String strHtml) {   
  1272.   
  1273.         try {   
  1274.   
  1275.             FileWriter fw = new FileWriter(strHtml);   
  1276.   
  1277.             fw.write(strText);   
  1278.   
  1279.             fw.close();   
  1280.   
  1281.         } catch (IOException e) {   
  1282.   
  1283.             // TODO Auto-generated catch block   
  1284.   
  1285.             e.printStackTrace();   
  1286.   
  1287.             System.out.println("解析mht失败");   
  1288.   
  1289.         }   
  1290.   
  1291.     }   
  1292.   
  1293.        
  1294.   
  1295.     private InternetAddress[] getInetAddresses(String emails) throws Exception {   
  1296.   
  1297.         ArrayList list = new ArrayList();   
  1298.   
  1299.         StringTokenizer tok = new StringTokenizer(emails, ",");   
  1300.   
  1301.         while (tok.hasMoreTokens()) {   
  1302.   
  1303.             list.add(tok.nextToken());   
  1304.   
  1305.         }   
  1306.   
  1307.         int count = list.size();   
  1308.   
  1309.         InternetAddress[] addresses = new InternetAddress[count];   
  1310.   
  1311.         for (int i = 0; i < count; i++) {   
  1312.   
  1313.             addresses[i] = new InternetAddress(list.get(i).toString());   
  1314.   
  1315.         }   
  1316.   
  1317.         return addresses;   
  1318.   
  1319.     }   
  1320.   
  1321.        
  1322.   
  1323.     class AttachmentDataSource implements DataSource {   
  1324.   
  1325.         private MimetypesFileTypeMap map = new MimetypesFileTypeMap();   
  1326.   
  1327.         private String strUrl;   
  1328.   
  1329.         private String strType;   
  1330.   
  1331.         private byte[] dataSize = null;   
  1332.   
  1333.            
  1334.   
  1335.         /**  
  1336.  
  1337.          * This is some content type maps.  
  1338.  
  1339.          */  
  1340.   
  1341.         private Map normalMap = new HashMap();   
  1342.   
  1343.         {   
  1344.   
  1345.             // Initiate normal mime type map   
  1346.   
  1347.             // Images   
  1348.   
  1349.             normalMap.put("image""image/jpeg");   
  1350.   
  1351.             normalMap.put("text""text/plain");   
  1352.   
  1353.         }   
  1354.   
  1355.   
  1356.   
  1357.         public AttachmentDataSource(String strUrl, String strType) {   
  1358.   
  1359.             this.strType = strType;   
  1360.   
  1361.             this.strUrl = strUrl;   
  1362.   
  1363.                
  1364.   
  1365.             strUrl = strUrl.trim();   
  1366.   
  1367.             strUrl = strUrl.replaceAll(" ""%20");   
  1368.   
  1369.             dataSize = JQuery.downBinaryFile(strUrl, null);   
  1370.   
  1371.         }   
  1372.   
  1373.            
  1374.   
  1375.         /**  
  1376.  
  1377.          * Returns the content type.  
  1378.  
  1379.          */  
  1380.   
  1381.         public String getContentType() {   
  1382.   
  1383.             return getMimeType(getName());   
  1384.   
  1385.         }   
  1386.   
  1387.            
  1388.   
  1389.         public String getName() {   
  1390.   
  1391.             char separator = File.separatorChar;   
  1392.   
  1393.             if( strUrl.lastIndexOf(separator) >= 0 )   
  1394.   
  1395.                  return strUrl.substring(strUrl.lastIndexOf(separator) + 1);   
  1396.   
  1397.              return strUrl;   
  1398.   
  1399.         }   
  1400.   
  1401.            
  1402.   
  1403.         private String getMimeType(String fileName) {   
  1404.   
  1405.             String type = (String)normalMap.get(strType);   
  1406.   
  1407.             if (type == null) {   
  1408.   
  1409.                 try {   
  1410.   
  1411.                     type = map.getContentType(fileName);   
  1412.   
  1413.                 } catch (Exception e) {   
  1414.   
  1415.                     // TODO: handle exception   
  1416.   
  1417.                 }   
  1418.   
  1419.                 System.out.println(type);   
  1420.   
  1421.                 // Fix the null exception   
  1422.   
  1423.                 if (type == null) {            
  1424.   
  1425.                     type = "application/octet-stream";   
  1426.   
  1427.                 }   
  1428.   
  1429.             }   
  1430.   
  1431.                
  1432.   
  1433.             return type;   
  1434.   
  1435.         }   
  1436.   
  1437.   
  1438.   
  1439.         public InputStream getInputStream() throws IOException {   
  1440.   
  1441.             // TODO Auto-generated method stub   
  1442.   
  1443.             if (dataSize == null)   
  1444.   
  1445.                 dataSize = new byte[0];   
  1446.   
  1447.             return new ByteArrayInputStream(dataSize);   
  1448.   
  1449.         }   
  1450.   
  1451.   
  1452.   
  1453.         public OutputStream getOutputStream() throws IOException {   
  1454.   
  1455.             // TODO Auto-generated method stub   
  1456.   
  1457.             return new java.io.ByteArrayOutputStream();   
  1458.   
  1459.         }   
  1460.   
  1461.   
  1462.   
  1463.     }   
  1464.   
  1465. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值