Conhecendo novas APIs e Frameworks, me deparo com o HtmlUnit…
Fiz um pequeno exemplo…
para baixar HtmlUnit --> http://htmlunit.sourceforge.net/
Aqui funcionou tranquilo…
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Andy11x - Membro GUJ
*/
public class LogandoGUJ {
private static HtmlPage dados;
public static void main(String[] args) throws Exception {
if(login("Usuario", "Senha")){ //<--- Coloque seu nome de usuario e senha
System.out.println("---------> Logado <---------\n");
dadosUserGuj();
}else{
System.out.println("---------> Não Logado <---------");
}
}
private static void dadosUserGuj() {
DomNodeList<DomElement> domElement = dados.getElementsByTagName("span");
System.out.println(domElement.get(3).asText());
System.out.println(domElement.get(2).asText());
}
private static WebClient webCliente() {
WebClient cliente = new WebClient(BrowserVersion.CHROME);
cliente.getOptions().setPrintContentOnFailingStatusCode(false);
cliente.getOptions().setCssEnabled(false);
cliente.getOptions().setThrowExceptionOnFailingStatusCode(false);
cliente.getOptions().setThrowExceptionOnScriptError(false);
return cliente;
}
private static String[] dadosPage() {
return new String[]{"http://www.guj.com.br/forums/list.java",
"",
"username",
"password",
"login"};
}
private static HtmlPage page() throws Exception {
return (HtmlPage)webCliente().getPage(dadosPage()[0]);
}
private static HtmlForm form() throws Exception {
return (HtmlForm)page().getFormByName(dadosPage()[1]);
}
private static Map<String, Object> submit() throws Exception {
Map<String, Object> map = new HashMap<>();
HtmlForm htmlform = form();
map.put("user", htmlform.getInputByName(dadosPage()[2]));
map.put("pass", htmlform.getInputByName(dadosPage()[3]));
map.put("submit", htmlform.getInputByName(dadosPage()[4]));
return map;
}
private static boolean login(String username, String password) throws Exception {
Map<String, Object> map = submit();
((HtmlTextInput)map.get("user")).setValueAttribute(username);
((HtmlPasswordInput)map.get("pass")).setValueAttribute(password);
dados = ((HtmlSubmitInput)map.get("submit")).click();
return dados.asText().contains("LOGOUT");
}
}