通过HTMLUnit与Java进行身份验证时遇到问题调试问题

如何解决通过HTMLUnit与Java进行身份验证时遇到问题调试问题

我无法通过网页上的HTMLUnit进行身份验证。我输入用户名和密码,然后单击登录,然后检查页面标题,它仍然是登录页面。所以我没有正确登录。

这是怎么回事?我正在尝试使用Fiddler和Charles进行调试,但是我看不到我的请求。此Java代码对给定网站进行身份验证是否有意义?有调试提示吗? 请帮我!谢谢。

我的代码:

package com.company;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.CookieManager;

public class Main {

  static WebClient webClient;
  static CookieManager cookieManager;
  static String username = "MyUsername";
  static String password = "MyPassword";

  @Before
  public static void init() throws Exception {
    webClient = new WebClient();
    cookieManager = new CookieManager();
    cookieManager = webClient.getCookieManager();
    cookieManager.setCookiesEnabled(true);
    webClient.getOptions().setTimeout(90000);
    webClient.setJavaScriptTimeout(90000);
  }

  @After
  public static void close() throws Exception {
    webClient.close();
    cookieManager.clearCookies();
  }

  public static void signIn() throws Exception {
    //Acquire location for URI,password,username,submitbutton
    HtmlPage page1 = webClient.getPage("https://h3c.mlspin.com/signin.asp#ath");


    HtmlForm form = page1.getFormByName("loginform");
    HtmlTextInput uName = form.getInputByName("user_name");
    HtmlPasswordInput passWord = form.getInputByName("pass");
    HtmlButton button = form.getFirstByXPath("//*[@id=\"loginForm\"]/table/tbody/tr[7]/td/button");

    uName.setValueAttribute(username);
    passWord.setValueAttribute(password);
    HtmlPage page2 = button.click();

    System.out.println("HTMLUNIT UserText : \n" + uName.getText());
    System.out.println("HTMLUNIT PassText : \n" + passWord.getText());

    System.out.println("Results p2   " + page2.getTitleText());
    System.out.println("Results p2   " + page2.getPage());
  }


  @Test
  public static void givenAClient_gatherInfo() throws Exception {
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setRedirectEnabled(true);
    webClient.getCache().setMaxSize(0);

  }

  public static void main(String[] args) throws Exception {

    init();
    givenAClient_gatherInfo();
    signIn();
    close();

  }
}
<!-- Latest compiled and minified CSS -->
<LINK href="/css/Signin.css" type=text/css rel=stylesheet>
<script language='javascript'>
  window.sessionStorage.clear();
</script>
<html>

<head>
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,shrink-to-fit=no">
  <meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
  <meta http-equiv="expires" content="0">
  <title>pinergy - Sign In</title>
  <link href="/style.asp" type="text/css" rel="stylesheet">
  <script type="text/javascript" src="/shared/scripts/3rdParty/jquery-3.3.1.min.js"></script>
  <script type="text/javascript" src="/shared/scripts/3rdParty/bootstrap-4.1.1/bootstrap.min.js"></script>
  <script type="text/javascript" src="/shared/scripts/cookieConsent.js?v=2"></script>
  <script language="JavaScript">
    var ath;
    ath = {}

    ;
    var isMobile = function() {
      return /(iphone|ipod|(android.*mobile)|blackberry|windows ce|palm|symbian|nexus 7|xoom|windows phone)/i.test(navigator.userAgent);
    }

    ;
    var isIPad = function() {
      return /(ipad)/i.test(navigator.userAgent);
    }

    function CheckSavePassword() {
      if (document.loginform.SavePassword.checked) {
        document.loginform.SavePassword.checked = false;
      } else {
        document.loginform.SavePassword.checked = true;
      }
    }

    function parseQueryString(queryString) {
      var QueryString = {};
      queryString = queryString.slice(queryString.indexOf("?") + 1);
      var qsArray = queryString.split("&");
      for (var i = 0; i < qsArray.length; i++) {
        var arr = qsArray[i].split("=");
        QueryString[arr[0]] = arr[1];
      }
      return QueryString;
    }

    if (window != top) {
      top.location.href = location.href;
    }
  </script>
  <style>
    body {
      padding: 0;
    }
    
    INPUT.login {
      height: 22px;
      border: 1px solid #808080;
      padding: 2px 4px;
      background-image: url('images/bg_input.gif');
    }
    
    .mobile {
      padding: 6px;
      align-content: center;
      align-self: center;
      width: 90%;
      height: auto;
      display: none;
      text-align: center;
      border: 4px solid #E7E7E7;
      border-radius: 15px;
      color: #444;
      margin: auto;
      background: -moz-linear-gradient(top,#FFFFFF,#E7E7E7);
      background: -ms-linear-gradient(#FFFFFF,#E7E7E7);
      background: -webkit-gradient(linear,left top,left bottom,from(#FFFFFF),to(#E7E7E7));
      max-width: 25rem;
    }
    
    .mobileButton {
      font-weight: bold;
      border-top: 1px outset grey;
      border-left: 1px outset grey;
      -moz-border-radius: 10px 10px 10px 10px;
      -webkit-border-radius: 10px 10px 10px 10px;
      border-radius: 10px 10px 10px 10px;
      -webkit-appearance: none;
      -moz-appearance: none;
      min-height: 2rem;
      /*width:90px;
            
            height:54px;
            font-family:Arial;
            font-size:x-large;*/
    }
    
    .yes {
      background-color: #FBAF41;
    }
    
    .no {
      background-color: #BEBEBE;
    }
    
    .mobileCheckTable {
      font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif !important;
    }
    
    .mobileCheckTable td {
      vertical-align: top;
    }
    
    .textContent {
      font-size: .9rem;
      text-align: center;
      font-weight: 500;
    }
    
    .textContent1Child {
      white-space: nowrap;
      padding-left: .5rem;
    }
    
    .mobilecheck {
      height: 1.2rem;
      width: 1.2rem;
      vertical-align: top;
      padding: 0;
      border: 1px solid rgba(0,0.3);
    }
    
    .mobilequest {
      margin: 0 auto;
      max-width: 20rem;
      box-sizing: border-box;
      float: left;
      padding-left: .5rem;
      padding-bottom: .5rem;
    }
    
    div#remember {
      font-size: 0.88rem;
    }
    
    .mls-bootstrap-font {
      font-size: 1rem;
      font-family: -apple-system,sans-serif;
    }
    
    .sm-remember {
      display: none;
    }
    
    @media only screen and (min-width: 476px) {
      .mobile {
        padding: 15px;
      }
      .sm-remember {
        display: initial;
      }
      .mobilequest {
        padding-bottom: 1rem;
      }
      .mobilequest,.textContent1Child {
        padding-left: 1rem;
      }
    }
    
    @media only screen and (min-width: 768px) {
      .mobilequest.textContent {
        font-size: 1.5rem !important;
      }
      .textContent1Child {
        font-size: 1.2rem !important;
      }
    }
    
    @media only screen and (min-width: 1024px) {
      .mobilequest.textContent {
        font-size: 1.6rem !important;
      }
      .textContent1Child {
        font-size: 1.2rem !important;
      }
    }
  </style>
  <link rel="icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
  <link rel="shortcut icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
  <link rel="stylesheet" type="text/css" href="css/addtohomescreen.css">
  <script src="Scripts/addtohomescreen.js"></script>
  <link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-120x120.png" type="image/x- 
 icon" sizes="120x120" />
  <link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-152x152.png" type="image/x- 
 icon" sizes="152x152" />
  <link rel="shortcut icon" href="images/apple-touch-icon-152x152.png" type="image/x-icon" sizes="152x152" />
  <link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-57x57.png" type="image/x- 
 icon" sizes="57x57" />
</head>

<body marginheight="0" marginwidth="0" topmargin="0" leftmargin="0">
  <table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="100%" height="100%">
        <form name="loginform" id="loginForm" method="POST" action="signin.asp" style="margin: 
 0px" onsubmit="return signInFn.loginFormOnSubmit();
">
          <input name="cxzvvfbvvalideguaueff" value="DT: 8/16/2020 8:18:40 PM" type="hidden"><input name="Page_Loaded" value="DT: 8/16/2020 9:25:16 PM" type="hidden">
          <table border="0" cellspacing="0" cellpadding="0" class="mls-login">
            <tr>
              <td><img src="images/MLSPIN_Logo.jpg" width="240" height="60" /></td>
            </tr>
            <tr>
              <td class="text-left pl-4"><span class="h4">Sign In to</span><img src="images/pinergy-logo.jpg" width="90" height="30" /></td>
            </tr>
            <tr>
              <td class="pl-2"><input class="form-control" type="text" style="width: 220px;" name="user_name" maxlength="8" value="MyUsername" placeholder="Enter Your Agent ID"></td>
            </tr>
            <tr>
              <td class="pl-2"><input class="form-control" type="password" style="width: 220px" name="pass" maxlength="20" placeholder="Password"></td>
            </tr>
            <tr>
              <td class="text-left pl-2"><a href="/MLS.Pinergy/auth/password/forgotpassword">Forgot your password?</a></td>
            </tr>
            <tr>
              <td class="text-left pl-2 mls-login-rem-me"><input type="checkbox" name="SavePassword" value="Y"><span onclick="CheckSavePassword();">Remember My Password</span></td>
            </tr>
            <tr>
              <td><button class="btn btn-sm btn-primary" type="submit">Sign In</button>
                <!--<input class="btn btn-sm btn-primary" type="submit" value="Sign In" name="signin"></td>--></tr>
          </table>
        </form>
        </td>
    </tr>
    <tr>
      <td>
        <footer class="mls-site-footer">
          <div class="footer-content">
            <div class="footer-icon MLSPINlogo mr-1"></div>
            <div class="mb-1">&copy;
              <span>MLS Property Information Network,Inc.</span></div>
            <div class="vert-bar">|</div>
            <div>900 Hartford Turnpike,fakeville,TN 01245 </div>
            <div class="vert-bar">|</div>
            <div>800-700-3189 </div>
            <div class="vert-bar">|</div>
            <div class="footer-content-group">
              <div class="d-inline"><a href="http://www.mlspin.com/downloads/WebsiteAccessNoticeForm.pdf" target="_blank">Access Notice</a></div>
              <div class="vert-bar d-inline">|</div>
              <div class="d-inline"><a href="http://www.mlspin.com/privacy_policy.aspx" target="_blank">Privacy Policy</a></div>
              <div class="vert-bar d-inline">|</div>
              <div class="d-inline"><a href="http://www.mlspin.com/copyright_policy.aspx" target="_blank">Copyright Policy</a></div>
            </div>
            <div class="vert-bar">|</div>
            <div class="footer-user-count">2190 users online right now!</div>
          </div>
        </footer>
      </td>
    </tr>
  </table>
  <div id="cookieConsentBootstrapModal" class="modal mls-bootstrap-font" role="dialog" aria-labelledby="cookieConsentTitle" aria-describedby="cookieConsentDesc" aria-hidden="true" data-backdrop="static" tabindex="-1">
    <div class="modal-dialog" role="document">
      <!-- Modal content-->
      <div class="modal-content mls-modal-bgcolor">
        <div class="modal-header">
          <h1 class="modal-title h5" id="cookieConsentTitle">This website uses cookies</h1>
        </div>
        <div class="modal-body" id="cookieConsentDesc">This website uses cookies for a number of purposes,including to enhance your browsing experience. Learn more about our use of cookies in our <a href="https://www.mlspin.com/privacy_policy.aspx" target="_blank">Privacy Policy</a>. </div>
        <div class="modal-footer"><button type="button" class="btn btn-sm btn-primary mls-js-cookie-consent-action" data-dismiss="modal">OK</button></div>
      </div>
    </div>
  </div>
  <script language="JavaScript">
    document.loginform.user_name.focus();
    alert("Incorrect password!\nPlease try again.");
  </script>
  <script>
    if (!window.location.hash.match('ath')) {
      addToHome = addToHomescreen({
        detectHomescreen: true,autostart: false,icon: true,lifespan: 15,maxDisplayCount: 1,appID: 'com.mlspin.MobileWeb'
      });
      addToHome.show();
      window.location.hash = '#ath';
    }
  </script>
  <script type="text/javascript">
    var signInFn = (function() {
        var _suppressCookieConsent = false;

        function _loginFormOnSubmit() {
          var isValid = true;
          if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
            isValid = false;
            cookieConsentUtil.showCookieBanner();
          }
          _enableDisableLoginForm();
          return isValid;
        }

        function _enableDisableLoginForm() {
          if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
            document.getElementById("loginForm").action = "signin.asp";
          } else {
            document.getElementById("loginForm").action = "validate_new.asp";
          }
        }

        function _focusOnFirstElement() {
          try {
            var focusable = $('button:visible,a[href]:visible,input:visible,select:visible,textarea:visible,[tabindex]:visible:not([tabindex="-1"])');
            if (focusable.length > 0) {
              var firstFocusable = focusable[0];
              firstFocusable.focus();
            }
          } catch (ex) {}
        }

        function _docOnReady() {
          //_focusOnFirstElement();
          cookieConsentUtil.init({
            onStoreCookieConsent: function() {
              _enableDisableLoginForm();
              setTimeout(_focusOnFirstElement,0);
            }
          });
          cookieConsentUtil.docOnReady();
          _enableDisableLoginForm();
        }
        return {
          loginFormOnSubmit: _loginFormOnSubmit,docOnReady: _docOnReady
        };
      }

      ());
    $(document).ready(function() {
        signInFn.docOnReady();
      }

    );
  </script>
</body>

</html>

解决方法

在javascript中有以下部分:

if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
    document.getElementById("loginForm").action="signin.asp";
}
else{                    
    document.getElementById("loginForm").action="validate_new.asp";
}

通过查看http请求,似乎validate_new.asp正在将302(重定向)返回到signin.asp。这可能有助于找到相关的请求。

我尝试了更深入的研究,但是我需要尝试运行您的代码,而我现在没有时间去做。如果我有时间的话,我会再来的,

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-