读书人

SWING兑现新浪微博客户端(1)自动登录

发布时间: 2012-12-23 11:28:15 作者: rapoo

SWING实现新浪微博客户端(1)自动登录功能

最近在做一些,基于浏览器的应用整合项目。使用到了DJNative (一种JAVA浏览器实现http://sourceforge.net/projects/djproject/files/DJ%20Native%20Swing/0.9.9%20preview/DJNativeSwing-SWT-0-9-9-20110224.zip/download),对于一些进行接口开发的业务整合系统,提供了一种不错的思路。周末兴趣所致,写了一个新浪微博自动登录的例子。
实现一下功能:1,如果已经登录过的用户,读取配置文件中的用户名密码,调用当前页面自动完成登录。
2,如果未登录用户提示用户输入用户名密码,在用户登录成功后自动截取用户名密码保存到配置文件。
3,当用户名密码出错时清楚已保存的用户名密码,提示用户重新登录。

第一次运行时 提示没有从配置文件中读取到用户名密码

?

"document.getElementById('password').value='"+password+"';" +LS+
"document.getElementById('login_submit_btn').click();";
e.getWebBrowser().executeJavascript(script);
}else{
String script="function saveuser(){" +LS+
"sendNSCommand('saveuser',document.getElementById('loginname').value,document.getElementById('password').value);"+LS+

"}" +LS+
"document.getElementById('login_submit_btn').attachEvent('onclick',saveuser);" +LS+
"alert('存储的用户名密码为空,请输入用户名密码')" +LS+
"";
e.getWebBrowser().executeJavascript(script);
e.getWebBrowser().removeWebBrowserListener(this);
e.getWebBrowser().addWebBrowserListener(new ReLoginListener());

}

}else{
System.out.println(e.getNewResourceLocation());
}
}
}

?
SWING兑现新浪微博客户端(1)自动登录功能

?

?

输入用户名密码:

?

SWING兑现新浪微博客户端(1)自动登录功能


输入用户名密码成功:成功登录


SWING兑现新浪微博客户端(1)自动登录功能

这时已将用户名密码保存到userProperties.properties中

SWING兑现新浪微博客户端(1)自动登录功能

?

再次运行时将自动完成新浪微博的登录!

完整的代码如下:

?

import java.awt.BorderLayout;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Properties;import javax.swing.BorderFactory;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.SwingUtilities;import chrriis.common.UIUtils;import chrriis.dj.nativeswing.swtimpl.NativeInterface;import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;import chrriis.dj.nativeswing.swtimpl.components.WebBrowserCommandEvent;import chrriis.dj.nativeswing.swtimpl.components.WebBrowserNavigationEvent;public class SSOSina extends JPanel {  protected static final String LS = System.getProperty("line.separator");   private static final  String  loginUrl="http://t.sina.com.cn";      private static  Properties  userProperties=new Properties();  public SSOSina() {    super(new BorderLayout());        InputStream in = this.getClass().getResourceAsStream("userProperties.properties");    if (in == null) {        in = Thread.currentThread().getContextClassLoader().getResourceAsStream("userProperties.properties");        if (in == null) {            in = this.getClass().getClassLoader().getResourceAsStream("userProperties.properties");        }    }        try {userProperties.load(in);} catch (IOException e1) {e1.printStackTrace();}        JPanel webBrowserPanel = new JPanel(new BorderLayout());    webBrowserPanel.setBorder(BorderFactory.createTitledBorder("DJNative JAVA浏览器实现 实现新浪微博自动登录"));    final JWebBrowser webBrowser = new JWebBrowser();    webBrowser.setBarsVisible(true);    webBrowser.setDefaultPopupMenuRegistered(true);    webBrowser.setStatusBarVisible(true);       webBrowser.navigate(loginUrl);    //单点登录自动提交监听器    class SaveUserListener extends WebBrowserAdapter{       @Override           public void commandReceived(WebBrowserCommandEvent e) {             String command = e.getCommand();             Object[] parameters = e.getParameters();             if("print".equals(command)) {               String html = (String)parameters[0] ;               System.out.println(html);             }             if("saveuser".equals(command)) {               String loginname = (String)parameters[0] ;               String password = (String)parameters[1] ;            userProperties.setProperty("loginname", loginname);             userProperties.setProperty("password", password);try {String runningURL = (new URL(SaveUserListener.class.getProtectionDomain().getCodeSource().getLocation(),".")).openConnection().getPermission().getName();userProperties.save(new   FileOutputStream(new File(runningURL+"userProperties.properties")),"changed");} catch (FileNotFoundException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();}                       }           }               }            class ReLoginListener extends WebBrowserAdapter{            public void locationChanged(WebBrowserNavigationEvent e) {         if (e.getNewResourceLocation().equals("http://t.sina.com.cn")){             userProperties.setProperty("loginname", "");                     userProperties.setProperty("password", "");               try {  String runningURL = (new URL(SaveUserListener.class  .getProtectionDomain().getCodeSource().getLocation(),  ".")).openConnection().getPermission().getName();  userProperties.save(new   FileOutputStream(new File(runningURL+"jdsclient_init.properties")),"changed");    } catch (FileNotFoundException e1) {  e1.printStackTrace();  } catch (IOException e1) {    e1.printStackTrace();  }                                                        String script="function saveuser(){" +LS+           "sendNSCommand('saveuser',document.getElementById('loginname').value,document.getElementById('password').value);"+LS+           "void(0);" +LS+           "}" +LS+           "document.getElementById('login_submit_btn').href=\"javascript:'saveuser()'\";document.getElementById('login_submit_btn').attachEvent('onclick',saveuser);" +LS+           "alert('用户名密码错误请重新输入');" +LS+           "";         e.getWebBrowser().executeJavascript(script);                 }                          }        }           class SsoListener extends WebBrowserAdapter{      public void locationChanged(WebBrowserNavigationEvent e) {      if (e.getNewResourceLocation().equals("http://t.sina.com.cn/")){    String loginname= userProperties.getProperty("loginname")  ;               String password= userProperties.getProperty("password")  ;               if ((loginname!=null &&!loginname.equals(""))  && (password!=null && !loginname.equals(""))){                String script="document.getElementById('loginname').value='"+loginname+"';" +LS+          "document.getElementById('password').value='"+password+"';" +LS+          "document.getElementById('login_submit_btn').click();";                 e.getWebBrowser().executeJavascript(script);               }else{                String script="function saveuser(){" +LS+                "sendNSCommand('saveuser',document.getElementById('loginname').value,document.getElementById('password').value);"+LS+                            "}" +LS+                "document.getElementById('login_submit_btn').attachEvent('onclick',saveuser);" +LS+                "alert('存储的用户名密码为空,请输入用户名密码')" +LS+                "";               e.getWebBrowser().executeJavascript(script);               e.getWebBrowser().removeWebBrowserListener(this);               e.getWebBrowser().addWebBrowserListener(new ReLoginListener());               }                  }else{      System.out.println(e.getNewResourceLocation());      }      }             }            webBrowser.addWebBrowserListener(new SaveUserListener());    webBrowser.addWebBrowserListener(new SsoListener());        webBrowserPanel.add(webBrowser, BorderLayout.CENTER);      add(webBrowserPanel, BorderLayout.CENTER);  }    public  InputStream loadResource(String name) {      InputStream in = this.getClass().getResourceAsStream(name);      if (in == null) {          in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);          if (in == null) {              in = this.getClass().getClassLoader().getResourceAsStream(name);          }      }      return in;  }    public static void main(String[] args) {    UIUtils.setPreferredLookAndFeel();    NativeInterface.open();    SwingUtilities.invokeLater(new Runnable() {      public void run() {        JFrame frame = new JFrame("测试新浪微博登录");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.getContentPane().add(new SSOSina(), BorderLayout.CENTER);        frame.setSize(800, 600);        frame.setLocationByPlatform(true);        frame.setVisible(true);      }    });    NativeInterface.runEventPump();      } }

?



/* * Christopher Deckers (chrriis@nextencia.net) * http://www.nextencia.net * * See the file "readme.txt" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. */package chrriis.dj.nativeswing.swtimpl.demo.examples.webbrowser;import java.awt.BorderLayout;import java.awt.Dialog;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.Window;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.image.BufferedImage;import javax.swing.BorderFactory;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.SwingUtilities;import chrriis.common.UIUtils;import chrriis.dj.nativeswing.swtimpl.NativeComponent;import chrriis.dj.nativeswing.swtimpl.NativeInterface;import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;/** * @author Christopher Deckers */public class FullPageCaptureExample extends JPanel {  private static final String LS = System.getProperty("line.separator");  private static final Dimension THUMBNAIL_SIZE = new Dimension(400, 300);  public FullPageCaptureExample() {    super(new BorderLayout());    JPanel webBrowserPanel = new JPanel(new BorderLayout());    webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));    final JWebBrowser webBrowser = new JWebBrowser();    webBrowser.navigate("http://www.google.com");    webBrowserPanel.add(webBrowser, BorderLayout.CENTER);    add(webBrowserPanel, BorderLayout.CENTER);    // Create an panel with a screen capture button.    JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));    JButton captureButton = new JButton("Full-page capture");    captureButton.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {        String result = (String)webBrowser.executeJavascriptWithResult(        "var width = 0;" + LS +        "var height = 0;" + LS +        "if(document.documentElement) {" + LS +        "  width = Math.max(width, document.documentElement.scrollWidth);" + LS +        "  height = Math.max(height, document.documentElement.scrollHeight);" + LS +        "}" + LS +        "if(self.innerWidth) {" + LS +        "  width = Math.max(width, self.innerWidth);" + LS +        "  height = Math.max(height, self.innerHeight);" + LS +        "}" + LS +        "if(document.body.scrollWidth) {" + LS +        "  width = Math.max(width, document.body.scrollWidth);" + LS +        "  height = Math.max(height, document.body.scrollHeight);" + LS +        "}" + LS +        "return width + '/' + height;");        // This may happen from time to time so we have to fail gracefully.        int index = result == null? -1: result.indexOf("/");        if(index < 0) {          JOptionPane.showMessageDialog(webBrowser, "An error occurred while capturing the full-page", "Full-page capture failure", JOptionPane.ERROR_MESSAGE);        } else {          NativeComponent nativeComponent = webBrowser.getNativeComponent();          Dimension originalSize = nativeComponent.getSize();          Dimension imageSize = new Dimension(Integer.parseInt(result.substring(0, index)), Integer.parseInt(result.substring(index + 1)));          // We add some artificial spacing because with scrollbars logic it is likely to be wrong...          imageSize.width = Math.max(originalSize.width, imageSize.width + 50);          imageSize.height = Math.max(originalSize.height, imageSize.height + 50);          nativeComponent.setSize(imageSize);          BufferedImage image = new BufferedImage(imageSize.width, imageSize.height, BufferedImage.TYPE_INT_RGB);          nativeComponent.paintComponent(image);          nativeComponent.setSize(originalSize);          Window window = SwingUtilities.getWindowAncestor(webBrowser);          JDialog dialog;          if(window instanceof Frame) {            dialog = new JDialog((Frame)window, "Full-page capture", true);          } else {            dialog = new JDialog((Dialog)window, "Full-page capture", true);          }          int tWidth = THUMBNAIL_SIZE.width;          int tHeight = THUMBNAIL_SIZE.height;          final ImageIcon imageIcon;          if(imageSize.width <= tWidth && imageSize.height <= tHeight) {            imageIcon = new ImageIcon(image);          } else {            float ratio1 = imageSize.width / (float)imageSize.height;            float ratio2 = tWidth / (float)tHeight;            int width = ratio1 > ratio2? tWidth: Math.round(tWidth * ratio1 / ratio2);            int height = ratio1 < ratio2? tHeight: Math.round(tHeight * ratio2 / ratio1);            imageIcon = new ImageIcon(image.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH));          }          dialog.getContentPane().add(new JLabel(imageIcon));          dialog.pack();          dialog.setLocationRelativeTo(window);          dialog.setVisible(true);        }      }    });    southPanel.add(captureButton);    add(southPanel, BorderLayout.SOUTH);  }  /* Standard main method to try that test as a standalone application. */  public static void main(String[] args) {    UIUtils.setPreferredLookAndFeel();    NativeInterface.open();    SwingUtilities.invokeLater(new Runnable() {      public void run() {        JFrame frame = new JFrame("DJ Native Swing Test");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.getContentPane().add(new FullPageCaptureExample(), BorderLayout.CENTER);        frame.setSize(800, 600);        frame.setLocationByPlatform(true);        frame.setVisible(true);      }    });    NativeInterface.runEventPump();  }}





12 楼 wenzhangli 2011-03-18 itcrown2005 写道 这,这,其实是。。。。。一种倒退

娱乐一把,不过在一些特定的应用范围里,可能会有一些特殊的用途。
比如,在桌面整合中,用户可以通过这种方式完成几乎所的有单点登录功能。
而相较于HTTPCLIENT的数据抓取,这种方式无疑,是一种更轻量级、适用性更强的方案。 13 楼 PROFANS 2011-09-17 博主,你好。其实我在考虑登录成功之后直接调用我们系统的浏览器去打开更登录成功的网站,而且是登录状态,一直纠结中,未能实现,能否指教一二?谢谢之前我就是用Swing做的用户界面,可以打开指定的网站,在项目里面可以登录成功,但是打开的网站根本没有登录信息,一直纠结中

读书人网 >编程

热点推荐