很多写软件的猿友,会有个需求就是本地登录。
比如写个抢购软件,在抢购之前把所有账号都登陆一下,把Cookie保存到本地,然后快抢购的时候直接读取本地的Cookie即可实现登录(总所周知,抢购前几分钟登录会卡)。
Java在这方面也有很多框架会实现,无需我们自己动手写代码。比如Memcache,OSCache框架等等,都可以实现将登陆后的Cookie对象序列化到本地或者其他的服务器上。但是我们自己写抢购软件,一个小小的序列化功能,也无需引用这些框架,自己完全可以搞定。
先贴代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
public class LoginCookies { private HttpClientLocal http; private String userName; public LoginCookies(HttpClientLocal http, String userName) { this.http = http; this.userName = userName; } /** * 序列化保存Cookie到当前本地 */ public void saveCookie() { try { String fileName = Globals.cookiesPath + "S" + Globals.softModel + "_" + userName + "_login.cookie"; File tempFile = new File(fileName); if (tempFile.exists()) { try { RandomAccessFile raf = new RandomAccessFile(tempFile, "rw"); raf.setLength(0); raf.close(); } catch (Exception e2) { e2.printStackTrace(); } }else{ tempFile.createNewFile(); } List<Cookie> cookies = http.GetHttpCookies(); if (cookies != null) { FileOutputStream os = new FileOutputStream(tempFile); ObjectOutputStream oos=new ObjectOutputStream(os); oos.writeObject(cookies); oos.close(); os.close(); } } catch (Exception e) { e.printStackTrace(); } } /** * 读取Cookie到Http里 * @return */ public boolean readCookie(){ try{ String fileName = Globals.cookiesPath + "S" + Globals.softModel + "_" + userName + "_login.cookie"; File tempFile = new File(fileName); if(!tempFile.exists()){//文件不存在 直接返回false return false; } FileInputStream fis = new FileInputStream(tempFile); ObjectInputStream ois = new ObjectInputStream(fis); List<Cookie> cookies = (List<Cookie>)ois.readObject(); if(cookies != null ){ for(Cookie c : cookies){ if(c != null){ http.addHttpCookie(c); } } return true; } }catch(Exception e){ e.printStackTrace(); } return false; } public static void main(String[] args) { Globals.softModel = 7; System.out.println(lc.readCookie()); } } |
序列化关键代码就是:
1 2 3 4 5 |
FileOutputStream os = new FileOutputStream(tempFile); ObjectOutputStream oos=new ObjectOutputStream(os); oos.writeObject(cookies); oos.close(); os.close(); |
其中的cookies就是需要序列化的对象了,当然,这个对象必须得可序列化对象(实现Serializable接口)。
反序列化的关键代码:
1 2 3 |
FileInputStream fis = new FileInputStream(tempFile); ObjectInputStream ois = new ObjectInputStream(fis); List<Cookie> cookies = (List<Cookie>)ois.readObject(); |
这样就可以带着本地Cookie去访问网页了,此方法仅供参考,对于有些网站是有效的,但是有些网站对Cookie的时间有限制,可能效果就会不太可观了。
转载请注明:刘召考的博客 » Java序列化保存对象到本地–实现本地登录