`
wenzhangli
  • 浏览: 5795 次
社区版块
存档分类
最新评论

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,当用户名密码出错时清楚已保存的用户名密码,提示用户重新登录。

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

 

写道
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
分享到:
评论
13 楼 PROFANS 2011-09-17  
博主,你好。其实我在考虑登录成功之后直接调用我们系统的浏览器去打开更登录成功的网站,而且是登录状态,一直纠结中,未能实现,能否指教一二?谢谢之前我就是用Swing做的用户界面,可以打开指定的网站,在项目里面可以登录成功,但是打开的网站根本没有登录信息,一直纠结中
12 楼 wenzhangli 2011-03-18  
itcrown2005 写道
  这,这,其实是。。。。。一种倒退


娱乐一把,不过在一些特定的应用范围里,可能会有一些特殊的用途。
比如,在桌面整合中,用户可以通过这种方式完成几乎所的有单点登录功能。
而相较于HTTPCLIENT的数据抓取,这种方式无疑,是一种更轻量级、适用性更强的方案。
11 楼 zzc0000 2011-03-17  
看看这个吧,不是swing 强大不强大,而是你会不会用的问题







10 楼 wenzhangli 2011-03-16  
sw1982 写道
这篇不错,通过介绍我去看了一下native swing,发现居然swing也发展到这么强大的分支了,居然可以处理html和js

例子中调用的还是本地浏览器的内核,native swing没有实现HTML和JS的解析。但调用SWT的控件后实现了更多一点的功能。
9 楼 sw1982 2011-03-15  
这篇不错,通过介绍我去看了一下native swing,发现居然swing也发展到这么强大的分支了,居然可以处理html和js
8 楼 Javac_MyLife 2011-03-15  
学习了。第一次接触DJNative。
7 楼 i2534 2011-03-15  
昨天看到flyingsaucer,也许可以直接从html生成图片
6 楼 wenzhangli 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();
  }

}

5 楼 ymkyve 2011-03-14  
不错,客户端的东西做的很少.DJNative没用过
4 楼 elan1986 2011-03-14  
很不错,那个浏览器很不错!
3 楼 itcrown2005 2011-03-14  
  这,这,其实是。。。。。一种倒退
2 楼 glamey 2011-03-14  
模拟的那个浏览器,能生成快照吗?
1 楼 zhaoshun0417 2011-03-14  
   这个很好,,去年的毕业设计是自动登陆和恢复系统,没思路。
看了这个。。原来是这样实现的

相关推荐

    java swing 模拟新浪微博

    简单的java swing 编写的新浪微博用户登陆客户端。 在本地运行时,需要自己修改config.properties中client_ID和client_SERCRET属性的值。这两个值需要自己通过注册得到。

    Java新浪微博客户端开发第六步(完结&amp;&amp;开源)

    在这个项目中,Java客户端为用户提供了一种在本地操作系统上访问和操作新浪微博的功能。 4. **开源软件**:开源意味着源代码对公众开放,任何人都可以查看、使用、修改和分发代码。该项目开源,意味着开发者可以...

    新浪微博模拟登陆

    本主题聚焦于使用Java实现对新浪微博的模拟登录,这对于数据分析、信息抓取或自动化测试等应用场景具有重要意义。 【描述】:“新浪微博模拟登陆源代码,java实现,微博数据抓取” 这段描述揭示了几个关键点: 1....

    iBeebo:第三方新浪微博客户端

    总的来说,iBeebo作为一款基于Java的第三方新浪微博客户端,它利用Java的优势,提供了跨平台的兼容性、丰富的功能和良好的用户体验。尽管我们无法详细探讨其源代码(压缩包名为iBeebo-master),但可以肯定的是,它...

    Java模拟登录新浪微博

    NULL 博文链接:https://tonyj.iteye.com/blog/1897604

    java swing udp 客户端与客户端 通讯

    java swing udp 客户端与客户端 通讯 两客户端 通过IP 端口 相互发消息通讯,swing界面

    java新浪微博(含源代码)

    在这个项目中,我们重点讨论基于Java实现的新浪微博API客户端,它提供了访问和交互微博数据的能力。 首先,Java是面向对象的编程语言,它的强大在于其丰富的类库和强大的社区支持。在开发微博应用时,可以使用如...

    sina-weibo.rar_新浪微博

    客户端可能包括了用户登录、发布微博、查看时间线、评论互动等基本功能。然而,描述也指出在“美化方面”做得不够好,这意味着用户界面可能不够吸引人或者缺乏良好的用户体验设计。 【标签】:“新浪微博”标签...

    swing发邮件客户端

    Swing邮件客户端是一种基于Java Swing库开发的桌面应用程序,它允许用户发送电子邮件,类似于流行的Foxmail客户端。Swing是Java的一个图形用户界面(GUI)工具包,提供了丰富的组件和功能,使得开发者可以创建出美观且...

    Java Swing组件写的游戏客户端.zip

    Java Swing组件写的游戏客户端Java Swing组件写的游戏客户端 Java Swing组件写的游戏客户端Java Swing组件写的游戏客户端 Java Swing组件写的游戏客户端Java Swing组件写的游戏客户端 Java Swing组件写的游戏客户端...

    新浪微博文字向下滚动效果

    今天我们将深入探讨如何实现“新浪微博文字向下滚动效果”,主要关注其在Java和样式方面的实现细节。 一、Java实现滚动效果 在Java中,我们可以使用Swing或JavaFX库来创建GUI应用,并实现文本滚动效果。虽然Java...

    sina.zip_CrazyitWeibo_sina_新浪微博

    "crazyitweibo"是项目的关键标识,"sina"和"新浪微博"表明项目与新浪的社交媒体平台——微博有直接关联,可能实现了登录、发布微博、浏览时间线、评论互动等基本功能。 【压缩包子文件的文件名称列表】仅有一个条目...

    rain12306-java swing实现12306客户端 无任何服务端依赖.zip

    《rain12306-java swing实现12306客户端》是一款基于Java Swing技术开发的12306火车票预订系统,它无需依赖任何服务端组件,完全由客户端程序独立完成用户登录、余票查询及个人订单管理等功能。这款软件展示了Java ...

    基于Java Swing 的FTP客户端程序

    在Java Swing FTP客户端中,我们需要实现以下核心功能: 1. **连接与断开** - 使用`FTPClient`类建立与FTP服务器的连接,设置登录凭据(如用户名和密码),并确保正确关闭连接。 2. **文件列表** - 获取远程目录的...

    用JAVA swing 模拟实现Ftp客户端的基本操作,可以看到上传下载的速度等.zip

    在Java编程领域,Swing库是用于构建图形用户界面(GUI)的重要工具,它提供了丰富的组件和功能,使得开发者能够创建美观且功能丰富的桌面应用程序。本项目是利用Java Swing模拟实现了一个FTP(File Transfer ...

    Java+Swing即时聊天系统,客户端和服务端,多线程,socket

    Java+Swing即时聊天系统是基于Java编程语言和Swing GUI库构建的,它提供了一个基本的实时通信平台,允许用户进行私聊、公聊以及接收用户上下线的通知。这个系统利用了Java的核心特性,包括多线程和网络编程,通过...

    Swing + Socket + 多线程 至尊QQ 客户端安装包

    Socket通信是实现客户端与服务器之间数据传输的核心技术。Socket是TCP/IP协议族的一部分,允许两个网络连接上的进程进行双向通信。在这个聊天应用中,客户端通过Socket连接到服务器,发送聊天消息并接收来自其他用户...

    java使用post登陆新浪微博并保存登陆后网页程序

    在Java编程环境中,使用POST方法登录新浪微博并保存登录后的网页是一项常见的任务,这涉及到网络请求、数据解析以及文件操作等多个技术领域。以下是一些相关的知识点: 1. **HTTP POST请求**:POST是HTTP协议中的一...

Global site tag (gtag.js) - Google Analytics