码迷,mamicode.com
首页 > 其他好文 > 详细

fdfjks

时间:2016-09-05 23:27:48      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:

  1 package com.hanqi;
  2 
  3 import java.io.File;
  4 import java.io.FileWriter;
  5 import java.io.IOException;
  6 import java.text.ParseException;
  7 import java.text.SimpleDateFormat;
  8 import java.util.ArrayList;
  9 import java.util.Date;
 10 import java.util.HashMap;
 11 import java.util.List;
 12 import java.util.Map;
 13 import java.util.Set;
 14 import java.util.regex.Matcher;
 15 import java.util.regex.Pattern;
 16 
 17 import org.json.JSONArray;
 18 import org.json.JSONException;
 19 import org.json.JSONObject;
 20 import org.jsoup.Jsoup;
 21 import org.jsoup.nodes.Document;
 22 import org.jsoup.nodes.Element;
 23 
 24 import com.alibaba.fastjson.JSON;
 25 import com.hanqi.util.Attachment;
 26 import com.hanqi.util.Common;
 27 import com.hanqi.util.HttpCompoentsUtil;
 28 import com.hanqi.util.Mail;
 29 
 30 public class Mail163 {
 31 
 32     private HttpCompoentsUtil httpUtil = new HttpCompoentsUtil();
 33     private String sid;
 34 
 35     //最新发送时间
 36     private Date lastSendDate;
 37     //已抓取邮件的mid集合
 38     private Set<String> setMid;
 39     //最近的采集邮件的mid
 40     private String lastMid;
 41 
 42     public Mail163() {
 43     }
 44     public static void main(String[] args) {
 45         Mail163 lession = new Mail163();
 46         lession.login("邮箱用户名", "密码");
 47         lession.mailBox();
 48     }
 49     public Mail163(String lastMid) {
 50         this.lastMid = lastMid;
 51     }
 52 
 53     public Mail163(Date lastSendDate) {
 54         this.lastSendDate = lastSendDate;
 55     }
 56 
 57     public Mail163(Set<String> setMid) {
 58         this.setMid = setMid;
 59     }
 60 
 61     
 62 
 63     
 64     
 65     
 66     // 获取邮件详细
 67     public void mailDetail(Mail m)
 68     {
 69         
 70         String content = mailContent(m.getId());
 71         
 72         //如果有附件,则进入执行
 73         if (m.isAttached())
 74         {        
 75         Map<String, String> params = new HashMap<String, String>();
 76         params.put("var", "<?xml version=\"1.0\"?>"
 77                 + "<object><string name=\"id\">" + m.getId() + "</string>"
 78                         + "<boolean name=\"header\">true</boolean>"
 79                         + "<boolean name=\"returnImageInfo\">true</boolean>"
 80                         + "<boolean name=\"returnAntispamInfo\">true</boolean>"
 81                         + "<boolean name=\"autoName\">true</boolean>"
 82                         + "<object name=\"returnHeaders\">"
 83                         + "<string name=\"Resent-From\">A</string>"
 84                         + "<string name=\"Sender\">A</string>"
 85                         + "<string name=\"List-Unsubscribe\">A</string>"
 86                         + "<string name=\"Reply-To\">A</string></object>"
 87                         + "<boolean name=\"supportTNEF\">true</boolean></object>");        
 88 
 89         Map<String, String> headers = new HashMap<String, String>();
 90         headers.put("Accept", "text/javascript");// 以JSON方式返回数据
 91         String result = httpUtil.post(Common.MailDetailURL + sid, params, headers);
 92 
 93         result = result.replaceAll("new Date\\(.*?\\)", "null");
 94 
 95         try {    
 96             //从json提取相应的信息
 97             JSONArray ja = new JSONObject(result)
 98                     .getJSONObject("var")
 99                     .getJSONArray("attachments");
100                 
101                 List<Attachment> la = new ArrayList<>();
102             
103             for (int i = 0; i < ja.length(); i++)
104             {                
105                 JSONObject jo = ja.getJSONObject(i);
106                 
107                 Attachment am = new Attachment(jo.getString("id"), m.getId());
108                 am.setContentLength(jo.getInt("contentLength"));
109                 am.setFileName(jo.getString("filename"));
110                 am.setContentType(jo.getString("contentType"));
111                 
112                 // 下载附件
113                 mailAttachment(m, am);
114                 
115                 la.add(am);
116             }
117             
118             m.setAttachments(la);    
119             
120         } catch (JSONException e) {
121 
122             e.printStackTrace();
123         }
124         }
125         
126         m.setContent(content);
127     }
128 
129     
130     
131     
132     
133     // 获取邮件内容
134     public String mailContent(String mid) {
135         Map<String, String> params = new HashMap<String, String>();
136         String result = httpUtil.post(Common.MailContentURL + mid, params);
137         
138 
139         Document doc = Jsoup.parseBodyFragment(result);
140 
141         Element el = doc.select("div").first();
142 
143         String str = "";
144 
145         if (el != null) {
146             str = el.text();
147         }
148 
149         return str;
150     }
151 
152     
153     //存储附件
154     public void mailAttachment(Mail mail, Attachment att) {
155         Map<String, String> params = new HashMap<String, String>();
156 
157         try {
158             String strFilePath = Common.DataFilePath;
159 
160             
161             String fileName = getFileName(mail);
162             
163             String attPath = strFilePath + fileName + "_attachment/";
164             
165             File file = new File(attPath);
166             //路径是否存在
167             if (!file.exists())
168             {
169                 file.mkdirs();
170             }
171             
172             file = new File(attPath, att.getId() + "_" + att.getFileName());
173             //文件是否存在
174             if (!file.exists())
175             {
176                 file.createNewFile();
177             }
178             
179             att.setSavefilePath(attPath);
180             att.setSaveFileName(file.getName());
181             
182             httpUtil.postStream(Common.MailAttach
183                     .replace("$part$", att.getId())
184                     .replace("$sid$", sid)
185                     .replace("$mid$", mail.getId()), params, file);
186             
187             // 生成MD5
188             att.setMd5(Common.getMd5(file));
189 
190         } catch (Exception ex) {
191             ex.printStackTrace();
192         }
193     }
194     
195     
196     
197     
198     
199 
200     public void mailBox() 
201     {
202         Map<String, String> params = new HashMap<String, String>();
203         params.put("var", "<?xml version=\"1.0\"?>" + "<object><int name=\"fid\">1</int>"
204                 + "<boolean name=\"skipLockedFolders\">false</boolean>" + "<string name=\"order\">date</string>"
205                 + "<boolean name=\"desc\">true</boolean>" + "<int name=\"start\">0</int><int name=\"limit\">150</int>"
206                 + "<boolean name=\"topFirst\">true</boolean>" + "<boolean name=\"returnTotal\">true</boolean>"
207                 + "<boolean name=\"returnTag\">true</boolean></object>");
208 
209         Map<String, String> headers = new HashMap<String, String>();
210         headers.put("Accept", "text/javascript");
211         String result = httpUtil.post(Common.MailBoxURL + sid, params, headers);
212         
213         // 匹配发送时间的格式
214         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
215         Pattern p=Pattern.compile("‘sentDate‘:new Date\\(.*?\\)"); 
216         //共匹配到的数据
217         Matcher ma=p.matcher(result);                        
218         List<Date> sentDate = new ArrayList<>();
219                 
220         while(ma.find())
221         { 
222             //得到所有内容
223               String group = ma.group(); 
224               //得到时间
225               group = group.replace("‘sentDate‘:new Date(", "").replace(")", "");
226               String[] date = group.split(",");
227               
228               try 
229               {
230                   //生成正确的时间格式
231                 sentDate.add(sdf.parse(date[0] + "-" + 
232                 date[1] + "-" + date[2] + " " +
233                 date[3] + ":" + date[4] + ":" + date[5]));
234             } 
235               catch (ParseException e) 
236               {
237                 e.printStackTrace();
238             }
239         } 
240         
241         
242 
243         // 匹配接收时间
244         p=Pattern.compile("‘receivedDate‘:new Date\\(.*?\\)"); 
245         ma=p.matcher(result);  
246         
247         List<Date> receivedDate = new ArrayList<>();
248     
249         while(ma.find())
250         { 
251               String group = ma.group(); 
252               group = group.replace("‘receivedDate‘:new Date(", "").replace(")", "");
253               String[] date = group.split(",");
254               
255               try
256               {
257                   receivedDate.add(sdf.parse(date[0] + "-" + 
258                 date[1] + "-" + date[2] + " " +
259                         date[3] + ":" + date[4] + ":" + date[5]));
260             }
261               catch (ParseException e) 
262               {
263                 e.printStackTrace();
264             }
265         } 
266         //去除不正确格式的数据
267         String resultJSON = result.replaceAll("new Date\\(.*?\\)", "null");
268             
269             
270         // 解析收件箱列表
271         List<Mail> lm = new ArrayList<Mail>();
272         try
273         {
274         
275             JSONArray ja = new JSONObject(resultJSON).getJSONArray("var");
276         
277             for (int i = 0; i < ja.length(); i++)
278             {
279                 JSONObject jo = ja.getJSONObject(i);
280                     
281                 Mail m = new Mail(jo.getString("id"));
282                 m.setFrom(jo.getString("from"));
283                 m.setTo(jo.getString("to"));
284                 m.setSubject(jo.getString("subject"));
285                     
286                 JSONObject flags = jo.getJSONObject("flags");
287                 //判断是否有附件
288                 if (flags.has("attached"))
289                 {
290                     m.setAttached(flags.getBoolean("attached"));
291                 }
292             
293                 m.setSentDate(sentDate.get(i));
294                 m.setReceivedDate(receivedDate.get(i));
295             
296                 lm.add(m);
297             }            
298         } 
299         
300         catch (Exception e)
301         {
302             e.printStackTrace();
303         }
304         
305         String lmid = lastMid;
306 
307         // 遍历收件箱所有邮件的集合
308         for (int n = 0; n < lm.size(); n++)
309         {
310             Mail m  = lm.get(n);
311             
312             if (n == 0)
313             {
314                 lmid = m.getId();
315             }
316 
317             // 是否读取邮件内容
318             boolean isRead = false;
319 
320             // 根据最近的mid
321             if (lastMid != null) 
322             {
323                 if (!m.getId().equals(lastMid)) 
324                 {
325                     isRead = true;
326                 }
327                 else 
328                 {
329                     break;// 结束遍历
330                 }
331             }
332             
333             // 根据最新发送的时间
334             else
335                 if (lastSendDate != null) 
336                 {
337                     Date sendDate = m.getSentDate();
338 
339                     if (sendDate.compareTo(lastSendDate) > 0)
340                     {
341                         isRead = true;
342                     }
343                     else
344                     {
345                         break;
346                     }
347                 }
348             
349     
350                 // 根据mid判断
351                 else if (setMid != null)
352                 {
353                     String mid = m.getId();
354 
355                     if (!setMid.contains(mid)) 
356                     {
357                         isRead = true;
358                     }
359                     else
360                     {
361                         break;
362                     }
363                 } 
364                 else 
365                 {
366                     isRead = true;
367                 }
368 
369             if (isRead) 
370             {
371                 //邮件详细信息
372                 mailDetail(m);                
373                 System.out.println("抓取:" + m);
374                 //最后进行保存
375                 saveMail(m);
376             }
377         }
378 
379         // 保存最近邮件的发送时间和保存最近邮件的mid
380         String midFilePath = Common.MidFilePath;
381 
382         try 
383         {
384             
385             File midPath = new File(midFilePath);
386 
387             if (!midPath.exists()) 
388             {
389                 midPath.mkdirs();
390             }
391 
392             File midFile = new File(midFilePath, Common.MidFileName);
393 
394             if (!midFile.exists())
395             {
396                 midFile.createNewFile();
397             }
398 
399             FileWriter fw = new FileWriter(midFile);
400             fw.write(lmid);
401             fw.close();
402         }
403         
404         catch (Exception e) 
405         {
406             e.printStackTrace();
407         }
408     }
409     
410     
411     
412     
413     
414     
415     private String getFileName(Mail mail)
416     {
417         String rtn = "";
418         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
419         String mid = mail.getId();
420         rtn = sdf.format(mail.getSentDate())
421         + "_" + mid.substring(mid.length() - 8);
422         
423         return rtn;
424     }
425 
426     
427     
428     
429     
430     private void saveMail(Mail mail) {
431         // 保存邮件到文件
432         // 流,文件名是时间戳
433         // 选择合适的格式,方便读取
434         String json = JSON.toJSONString(mail);
435 
436 
437         try {
438 
439             String strFilePath = Common.DataFilePath;
440 
441             
442 
443             File mailPath = new File(strFilePath);
444 
445             if (!mailPath.exists()) {
446                 mailPath.mkdirs();
447             }
448 
449             File file = new File(strFilePath, getFileName(mail));
450 
451             if (!file.exists()) {
452                 file.createNewFile();
453             }
454 
455             FileWriter fw = new FileWriter(file);
456 
457             fw.write(json);
458 
459             fw.close();
460 
461         } catch (IOException e) {
462             // TODO 自动生成的 catch 块
463             e.printStackTrace();
464         }
465     }
466 
467     
468     
469     
470     
471     public void login(String username, String password) {
472         Map<String, String> params = new HashMap<String, String>();
473         params.put("ds", "mail163_letter");
474         params.put("from", "web");
475         params.put("funcid", "loginone");
476         params.put("iframe", "1");
477         params.put("language", "-1");
478         params.put("passtype", "1");
479         params.put("product", "mail163");
480         params.put("net", "c");
481         params.put("stype", "-1");
482         params.put("race", "167_158_146_gz");
483         params.put("uid", "osLoadLession@163.com");
484         params.put("savelogin", "0");
485         params.put("url2", "http://mail.163.com/errorpage/error163.htm");
486         params.put("username", username);
487         params.put("password", password);
488 
489         String s = httpUtil.post(Common.LoginURL, params).trim();
490         
491         int i = s.indexOf("http://");
492         String mainUrl = s.substring(i, s.indexOf("\";</script>"));
493         httpUtil.get(mainUrl);
494         sid = httpUtil.getCookie("Coremail.sid");
495         
496     }
497 }
  1 package com.hanqi_1;
  2 import java.io.IOException;
  3 import java.io.InterruptedIOException;
  4 import java.net.UnknownHostException;
  5 import java.security.cert.CertificateException;
  6 import java.security.cert.X509Certificate;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 import java.util.Map;
 10  
 11 import javax.net.ssl.SSLContext;
 12 import javax.net.ssl.SSLException;
 13  
 14 import org.apache.http.HttpEntity;
 15 import org.apache.http.HttpEntityEnclosingRequest;
 16 import org.apache.http.HttpRequest;
 17 import org.apache.http.HttpResponse;
 18 import org.apache.http.NameValuePair;
 19 import org.apache.http.client.HttpRequestRetryHandler;
 20 import org.apache.http.client.config.CookieSpecs;
 21 import org.apache.http.client.config.RequestConfig;
 22 import org.apache.http.client.entity.UrlEncodedFormEntity;
 23 import org.apache.http.client.methods.CloseableHttpResponse;
 24 import org.apache.http.client.methods.HttpGet;
 25 import org.apache.http.client.methods.HttpPost;
 26 import org.apache.http.client.protocol.HttpClientContext;
 27 import org.apache.http.config.RegistryBuilder;
 28 import org.apache.http.conn.ConnectTimeoutException;
 29 import org.apache.http.conn.ConnectionKeepAliveStrategy;
 30 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 31 import org.apache.http.conn.ssl.SSLContextBuilder;
 32 import org.apache.http.conn.ssl.TrustStrategy;
 33 import org.apache.http.cookie.Cookie;
 34 import org.apache.http.cookie.CookieOrigin;
 35 import org.apache.http.cookie.CookieSpec;
 36 import org.apache.http.cookie.CookieSpecProvider;
 37 import org.apache.http.cookie.MalformedCookieException;
 38 import org.apache.http.impl.client.BasicCookieStore;
 39 import org.apache.http.impl.client.CloseableHttpClient;
 40 import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
 41 import org.apache.http.impl.client.HttpClients;
 42 import org.apache.http.impl.cookie.BestMatchSpecFactory;
 43 import org.apache.http.impl.cookie.BrowserCompatSpec;
 44 import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
 45 import org.apache.http.message.BasicNameValuePair;
 46 import org.apache.http.protocol.HttpContext;
 47 import org.apache.http.util.EntityUtils;
 48  
 49 /**
 50  * @author bangis
 51  * 
 52  */
 53 public class HttpCompoentsUtil {
 54     private final String _DEFLAUT_CHARSET = "utf-8";
 55     private CloseableHttpClient httpClient;
 56  
 57     /**
 58      * 设置超时,毫秒级别
 59      */
 60     private RequestConfig requestConfig = RequestConfig.custom()
 61             .setSocketTimeout(1000).setConnectTimeout(1000).build();
 62     private BasicCookieStore cookieStore = new BasicCookieStore();
 63     {
 64         try {
 65             // 保持连接时长
 66             ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {
 67  
 68                 @Override
 69                 public long getKeepAliveDuration(HttpResponse response,
 70                         HttpContext context) {
 71                     long keepAlive = super.getKeepAliveDuration(response,
 72                             context);
 73                     if (keepAlive == -1) {
 74                         // 如果服务器没有设置keep-alive这个参数,我们就把它设置成5秒
 75                         keepAlive = 5000;
 76                     }
 77                     return keepAlive;
 78                 }
 79  
 80             };
 81             // 重试机制
 82             HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
 83                 public boolean retryRequest(IOException exception,
 84                         int executionCount, HttpContext context) {
 85                     if (executionCount >= 5) {
 86                         // 如果已经重试了5次,就放弃
 87                         return false;
 88                     }
 89                     if (exception instanceof InterruptedIOException) {
 90                         // 超时
 91                         return false;
 92                     }
 93                     if (exception instanceof UnknownHostException) {
 94                         // 目标服务器不可达
 95                         return false;
 96                     }
 97                     if (exception instanceof ConnectTimeoutException) {
 98                         // 连接被拒绝
 99                         return false;
100                     }
101                     if (exception instanceof SSLException) {
102                         // ssl握手异常
103                         return false;
104                     }
105                     HttpClientContext clientContext = HttpClientContext
106                             .adapt(context);
107                     HttpRequest request = clientContext.getRequest();
108                     boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
109                     if (idempotent) {
110                         // 如果请求是幂等的,就再次尝试
111                         return true;
112                     }
113                     return false;
114                 }
115  
116             };
117             CookieSpecProvider easySpecProvider = new CookieSpecProvider() {
118  
119                 public CookieSpec create(HttpContext context) {
120  
121                     return new BrowserCompatSpec() {
122                         @Override
123                         public void validate(Cookie cookie, CookieOrigin origin)
124                                 throws MalformedCookieException {
125                             // Oh, I am easy
126                         }
127                     };
128                 }
129  
130             };
131             SSLContext sslContext;
132             sslContext = new SSLContextBuilder().loadTrustMaterial(null,
133                     new TrustStrategy() {
134                         // 信任所有
135                         public boolean isTrusted(X509Certificate[] chain,
136                                 String authType) throws CertificateException {
137                             return true;
138                         }
139                     }).build();
140             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
141                     sslContext);
142  
143             RegistryBuilder
144                     .<CookieSpecProvider> create()
145                     .register(CookieSpecs.BEST_MATCH,
146                             new BestMatchSpecFactory())
147                     .register(CookieSpecs.BROWSER_COMPATIBILITY,
148                             new BrowserCompatSpecFactory())
149                     .register("easy", easySpecProvider).build();
150  
151             RequestConfig globalConfig = RequestConfig.custom()
152                     .setCookieSpec("easy").build();
153  
154             httpClient = HttpClients.custom()
155                     .setKeepAliveStrategy(keepAliveStrat)
156                     .setRetryHandler(retryHandler)
157                     .setDefaultRequestConfig(globalConfig)
158                     .setDefaultCookieStore(cookieStore)
159                     // .setSslcontext(sslContext)
160                     .build();
161         } catch (Exception e) {
162             e.printStackTrace();
163         }
164     }
165  
166     public void setTimeOut(int socketTimeOut, int connectTimeOut) {
167         requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeOut)
168                 .setConnectTimeout(connectTimeOut).build();
169     }
170  
171     public String get(String url) {
172         return get(url, _DEFLAUT_CHARSET);
173     }
174  
175     public String get(String url, String charset) {
176         return get(url, null, charset);
177     }
178  
179     public String get(String url, Map<String, String> headers, String charset) {
180         HttpClientContext context = HttpClientContext.create();
181         context.setCookieStore(cookieStore);
182         String useCharset = charset;
183         if (charset == null) {
184             useCharset = _DEFLAUT_CHARSET;
185         }
186         HttpGet httpGet = new HttpGet(url);
187         if (headers != null) {
188             for (String key : headers.keySet()) {
189                 httpGet.setHeader(key, headers.get(key));
190             }
191         }
192         httpGet.setConfig(requestConfig);
193         try {
194             CloseableHttpResponse response = httpClient.execute(httpGet,
195                     context);
196             try {
197                 HttpEntity entity = response.getEntity();
198                 return EntityUtils.toString(entity, useCharset);
199             } finally {
200                 response.close();
201             }
202         } catch (Exception e) {
203             e.printStackTrace();
204         }
205         return null;
206     }
207  
208     public String post(String url, Map<String, String> params) {
209         return post(url, params, null, null);
210     }
211  
212     public String post(String url, Map<String, String> params,
213             Map<String, String> headers) {
214         return post(url, params, headers, null);
215     }
216  
217     public String post(String url, Map<String, String> params, String charset) {
218         return post(url, params, null, charset);
219     }
220  
221     public String post(String url, Map<String, String> params,
222             Map<String, String> headers, String charset) {
223         HttpClientContext context = HttpClientContext.create();
224         context.setCookieStore(cookieStore);
225         String useCharset = charset;
226         if (charset == null) {
227             useCharset = _DEFLAUT_CHARSET;
228         }
229         try {
230             HttpPost httpPost = new HttpPost(url);
231             if (headers != null) {
232                 for (String key : headers.keySet()) {
233                     httpPost.setHeader(key, headers.get(key));
234                 }
235             }
236             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
237             if (params != null) {
238                 for (String key : params.keySet()) {
239                     nvps.add(new BasicNameValuePair(key, params.get(key)));
240                 }
241                 httpPost.setEntity(new UrlEncodedFormEntity(nvps));
242             }
243             httpPost.setConfig(requestConfig);
244             CloseableHttpResponse response = httpClient.execute(httpPost,
245                     context);
246             try {
247                 HttpEntity entity = response.getEntity();
248                 return EntityUtils.toString(entity, useCharset);
249             } finally {
250                 response.close();
251             }
252         } catch (Exception e) {
253             e.printStackTrace();
254         }
255         return null;
256     }
257  
258     public String getCookie(String key) {
259         List<Cookie> cookies = cookieStore.getCookies();
260         if (cookies != null) {
261             for (Cookie c : cookies) {
262                 if (c.getName().equals(key)) {
263                     return c.getValue();
264                 }
265             }
266         }
267         return null;
268     }
269  
270     public void printCookies() {
271         System.out.println("---查看当前Cookie---");
272         List<Cookie> cookies = cookieStore.getCookies();
273         if (cookies != null) {
274             for (Cookie c : cookies) {
275                 System.out.print(c.getName() + "         :" + c.getValue());
276                 System.out.print("  domain:" + c.getDomain());
277                 System.out.print("  expires:" + c.getExpiryDate());
278                 System.out.print("  path:" + c.getPath());
279                 System.out.println("    version:" + c.getVersion());
280             }
281         }
282     }
283  
284 }
package com.hanqi;

import java.io.File;
import java.io.FileReader;
import org.json.JSONObject;
import com.hanqi.util.Common;

public class MailRun 
{
    public static void main(String[] args)
    {
        
        try 
        {

            while (true)
            {
                
                String strFileName = Common.AccountFileName;
                String strFilePath = Common.AccountFilePath;


                File fa = new File(strFilePath, strFileName);
                
                //如果account.json文件存在,从account.json文件中读出数据
                if (fa.exists())
                {

                    FileReader fr = new FileReader(fa);

                    char[] cbuf = new char[1024];

                    int i = 0;

                    String str = "";

                    if ((i = fr.read(cbuf)) > 0) 
                    {
                        str += new String(cbuf, 0, i);
                    }

                    fr.close();
                    
                    if (str != null && str.length() > 0)
                    {
                        //解析从account.json文件中读出来的json格式的数据
                        JSONObject jo = new JSONObject(str).getJSONObject("account");

                        String username = jo.getString("username");
                        String password = jo.getString("password");

                        System.out.println("username=" + username + " password=" + password);

                        // 获取最近的发送时间
                        // 最近的mid
                        String lastMid = null;

                        String midFilePath = Common.MidFilePath;


                        File midPath = new File(midFilePath);
                        //判断mid路径是否存在,不存在则创建
                        if (!midPath.exists())
                        {
                            midPath.mkdirs();
                        }
                        else 
                        {
                            File midFile = new File(midFilePath, Common.MidFileName);
                            //判断mid.txt文件是否存在,不存在则创建
                            if (!midFile.exists())
                            {
                                midFile.createNewFile();
                            } 
                            
                            else
                            {
                                //从mid.txt文件中提取数据
                                FileReader frmid = new FileReader(midFile);

                                char[] c = new char[1024];

                                int m = 0;

                                lastMid = "";

                                while ((m = frmid.read(c)) > 0)
                                {
                                    lastMid += new String(c, 0, m);
                                }

                                frmid.close();
                            }
                        }

                        System.out.println("lastMid = " + lastMid);

                        Mail163 spider = new Mail163(lastMid);

                        // 登录
                        spider.login(username, password);

                        // 得到收件箱
                        spider.mailBox();
                    }
                }
                else
                {
                    System.out.println("account.json文件不存在");
                }

                System.out.println("休眠中");

                Thread.sleep(Common.SleepTime);
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }

}

 

fdfjks

标签:

原文地址:http://www.cnblogs.com/kekecom/p/5843894.html

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