2015-11-05 102 views
1

你好我是HtmlUnit的新手,我在编码这个问题上有问题。根据此代码我无法登录我错过了什么?这里是我的代码,例如我不想登录该网址。请检查我正在调试很长时间的代码。谢谢。我想单元测试它是否可以在登录后下载excel文件,然后将其写入流中。该网址是直播网站。请问你能帮帮我吗。在你可以下载文件之前,你需要登录这就是我现在的工作,但无法登录。HtmlUnit无法自动登录网站

String url = "https://www.frw.co.uk/login"; 
    final WebClient webClient = new WebClient(BrowserVersion.CHROME); 
    webClient.getOptions().setThrowExceptionOnScriptError(false); 
    webClient.getOptions().setJavaScriptEnabled(true); 

    try { 

     HtmlPage login = webClient.getPage(url);//button.click(); 

     final HtmlForm form = (HtmlForm) login.getElementById("loginForm"); 

     form.getInputByName("j_username").setValueAttribute("[email protected]"); 
     form.getInputByName("j_password").setValueAttribute("examplePassword"); 

     HtmlPage reslogin = form.getInputByValue("Login").click(); 

     final HtmlPage downloadPage = reslogin.getAnchorByText("Download Wine List").click(); 

     final HtmlPage p = downloadPage.getPage(); 


     WebResponse response2 = p.getWebResponse(); 
     InputStream is = response2.getContentAsStream(); 
     OutputStream outputStream = new FileOutputStream(new File(fileTarget)); 

     int read = 0; 
     byte[] bytes = new byte[1024]; 

     while ((read = is.read(bytes)) != -1) { 
      outputStream.write(bytes, 0, read); 
     } 
     outputStream.flush(); 
     outputStream.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    webClient.closeAllWindows(); 
+1

好,我还没有看到头了会后悔的,这和感谢! :) –

回答

0

也许尝试添加自动重定向与cookieManager

webClient.getOptions().setRedirectEnabled(true); 
webClient.getCookieManager().setCookiesEnabled(true); 
+0

仍然无法登录。我试图在登录页面上仍然将文本输出为文本。 –