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

SWING实现新浪微博客户端(2)提取关注好友信息

阅读更多
思路:
当用户登录完成后,(登录问题请参见,SWING实现新浪微博客户端(1)自动登录功能 )
1,模拟用户动作自动进入关注好友页面
2,根据关注好友页面结构提取关注好友的用户信息
3,将用户信息发送到后台,(例子中是在CONSOL中输出)

一,分析URL地址结构通过分析得知关注用户的URL地址为 http://t.sina.com.cn/2023096077/follow
而登录成功后的地址为



二,根据关注好友页面结构提取关注好友的用户信息





三,将用户信息发送到后台,(例子中是在CONSOL中输出)






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 GetUserListener extends WebBrowserAdapter{
    	  public void locationChanged(WebBrowserNavigationEvent e) {
    		
    		  //判断登录成功进入首页
    			 if( e.getWebBrowser().getPageTitle().indexOf("我的首页 ")>-1){
    				 String url=e.getNewResourceLocation();
    				String id=url.substring(url.lastIndexOf("/")+1, url.length()); 
    				 e.getWebBrowser().navigate("http://t.sina.com.cn/"+id+"/follow");//跳转到用户关注页面
    			 }
    	
    		  if (e.getNewResourceLocation().endsWith("/follow")){
    			  
    			  //首先重写App.followcancel方法,修改为输出到控制台的日志
    			  //跟据HTML规则提取关注用户HTML,再模拟点击
  	   	             String script="var tagName='a';" +
  	   	             		" App.followcancel=function(id,div,type,name,sex)" +
  	   	             		"{" +
  	   	             		"sendNSCommand('print','id='+id+';'+'name='+name)" +
  	   	             		"};" +
  	   	             		"var allA=document.all.tags(tagName);" +
  	   	             		"for(var i=0 ;i<allA.length;i++){" +
  	   	             		"if (allA[i].outerHTML.indexOf('App.followcancel(')>-1)" +
  	   	             		"{" +
  	   	             		"allA[i].click();" +
  	   	             		"sendNSCommand('print',allA[i].outerHTML)" +
  	   	             		"}" +
  	   	             		"}";
  	                 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);
	              //此处为修改代码
	                 
	                 
	                 e.getWebBrowser().removeWebBrowserListener(this);//关闭当前监听
	            
	                
	                //此处为修改代码
   	            }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());
    webBrowser.addWebBrowserListener(new GetUserListener());//添加GetUserListener
    
    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();
    
  }
 

}

  • 大小: 93.7 KB
  • 大小: 212.1 KB
  • 大小: 209 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics