论坛首页 Java企业应用论坛

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

浏览 16790 次
精华帖 (0) :: 良好帖 (6) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-03-13  

最近在做一些,基于浏览器的应用整合项目。使用到了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,当用户名密码出错时清楚已保存的用户名密码,提示用户重新登录。

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

 

写道
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());
}
}
}

 
第一次登录提示没有获取到配置文件中的用户

 

 

输入用户名密码:

 

输入用户名密码:


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


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

 

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

完整的代码如下:

 

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();
    
  }
 

}

 

  • 大小: 81.9 KB
  • 大小: 130.6 KB
  • 大小: 111.1 KB
  • 大小: 39 KB
   发表时间:2011-03-14  
   这个很好,,去年的毕业设计是自动登陆和恢复系统,没思路。
看了这个。。原来是这样实现的
0 请登录后投票
   发表时间:2011-03-14  
模拟的那个浏览器,能生成快照吗?
0 请登录后投票
   发表时间:2011-03-14  
  这,这,其实是。。。。。一种倒退
0 请登录后投票
   发表时间:2011-03-14  
很不错,那个浏览器很不错!
0 请登录后投票
   发表时间:2011-03-14  
不错,客户端的东西做的很少.DJNative没用过
0 请登录后投票
   发表时间:2011-03-14  
glamey 写道
模拟的那个浏览器,能生成快照吗?




/*
 * 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();
  }

}

  • 大小: 51.8 KB
0 请登录后投票
   发表时间:2011-03-15  
昨天看到flyingsaucer,也许可以直接从html生成图片
0 请登录后投票
   发表时间:2011-03-15  
学习了。第一次接触DJNative。
0 请登录后投票
   发表时间:2011-03-15  
这篇不错,通过介绍我去看了一下native swing,发现居然swing也发展到这么强大的分支了,居然可以处理html和js
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics