使用java和htmlunit获取vbulletin中的用户组

时间:2014-02-21 14:19:01

标签: java login htmlunit vbulletin

我正在开发一个登录系统,用于检查用户是否在特定用户组中。

如果用户在“访问”用户组中,那么我想向他们显示下一个表单。如果他们在用户组“注册用户”中,它将显示“抱歉,您没有访问权限”

这是我目前的代码:这将使用表单上显示的2个文本框登录。

我知道我不应该叫“gettext();”在密码字段但我不知道如何编码它所以htmlunit理解字符而不是放入数组的字符如果我写“getpassword()”

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package testmysql.gui;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;

/**
 *
 * @author Kjetil
 */
public class Login extends javax.swing.JFrame {

    public String setuser;
    public String setpass;
    public char[] input;
    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
        setLocationRelativeTo(null);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        txtboxPass = new javax.swing.JPasswordField();
        txtboxUser = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));

        txtboxPass.setText("jPasswordField1");
        getContentPane().add(txtboxPass, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1));

        txtboxUser.setText("jTextField1");
        getContentPane().add(txtboxUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


         setuser = txtboxUser.getText();
         setpass = txtboxPass.getText();

         Login();

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JPasswordField txtboxPass;
    private javax.swing.JTextField txtboxUser;
    // End of variables declaration                   





private void Login()
{



        try {
            WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false); // I think this speeds the thing up
            webClient.getOptions().setRedirectEnabled(true);
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            webClient.getCookieManager().setCookiesEnabled(true);

            String url = "http://svergja.com/forum";
            String name = setuser;
            String pass = setpass;

            HtmlPage page = webClient.getPage(url);

            System.out.println(
                    "1st page : " + page.asText());

            HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");
            HtmlInput uName = (HtmlInput) form.getByXPath("//*[@id=\"navbar_username\"]").get(0);

            uName.setValueAttribute(name);
            HtmlPasswordInput password = (HtmlPasswordInput) form.getByXPath("//*[@id=\"navbar_password\"]").get(0);

            password.setValueAttribute(setpass);
            HtmlSubmitInput button = form.getInputByValue("Log in"); 
            //(HtmlSubmitInput) form.getByXPath("//*[@id=\"loginbutton\"]").get(0);

            WebWindow window = page.getEnclosingWindow();
            button.click();


            while (window.getEnclosedPage() == page) {
                // The page hasn't changed.
                Thread.sleep(500);
            }
// This loop above will wait until the page changes.
            page = (HtmlPage) window.getEnclosedPage();

            System.out.println(
                    "2nd Page : " + page.asText());

            webClient.closeAllWindows();
        } catch (Exception ex) {
        }



}


}

如果登录成功,我想开始检查用户的用户组ID。如果我登录,我的用户组是管理员。我将添加一个测试用户,以便您自己登录并查看。

(以此身份登录“您将进入用户组(”注册用户“)”)

论坛网址:http://svergja.com/forum

用户名:stackoverflow

密码:stackit123

(测试用户信息)

1 个答案:

答案 0 :(得分:1)

成功登录后,使用锚点击配置文件链接,然后使用span获取用户组。 代码的更改将是:

   private void Login() throws FailingHttpStatusCodeException, MalformedURLException, IOException
        {
            WebClient client = new WebClient();
            client.setJavaScriptEnabled(false);
            HtmlPage page = client.getPage("http://svergja.com/forum/");

            HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");

            HtmlTextInput username = (HtmlTextInput) page.getElementById("navbar_username");
                username.setValueAttribute("stackoverflow");
            HtmlPasswordInput password = (HtmlPasswordInput) page.getElementById("navbar_password");
                password.setValueAttribute("stackit123");
            HtmlSubmitInput button = form.getInputByValue("Log in"); 
            page = button.click();

            List<HtmlAnchor> anchorList = page.getAnchors();
                for (HtmlAnchor htmlAnchor : anchorList) {
                    if(htmlAnchor.getAttribute("href").contains("member.php?"))
                    {
                        page = htmlAnchor.click();
                    }
                }

                HtmlSpan span = (HtmlSpan) page.getElementById("userinfo");
                DomNodeList<DomNode> nodeList = span.getChildNodes();

                    for (DomNode domNode : nodeList) {

                        NamedNodeMap map = domNode.getAttributes();
                        Node node = map.getNamedItem("class");
                          if(node != null && node.getNodeValue() != null && node.getNodeValue().equals("usertitle"))
                          {
                                System.out.println("The usergroup is "+domNode.getTextContent());
                          }
                    }
            }