Pessoal o problema é o seguinte: aqui no trampo precisamos fazer o download da lista de telefones que foram cadastrados para não receber ligações de empresas oferecendo serviços. Já existe um batch que lê e atualiza o banco como essas informações. Inicialmente fiz um batch em PHP e funcionou tudo certo, mas como o servidor do batch só tem o jre precisamos reescrever em java. Em java, todos os downloads que não é necessário fazer o login funcionou blz, mas os que precisam estar com a sessão aberta antes de fazer o download ai acontece o problema. Já tentei o CookieManager com o CookieHandler, já tentei pegar o cookie “na mão” e passar para a próxima requisição e nada funcionou. O estranho é que a página de resposta vem dizendo: “Seu navegador esta com os cookies desabilitados”, em outro caso faz o login mas na hora de fazer o download o cookie gerado não é válido, em outro não gera cookie nenhum. Resumindo o problema esta em conseguir persistir a sessão. Os códigos são os seguintes:
O código de teste:
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import proxy.ProxySettings;
import proxy.SimpleAuthenticator;
public class AL {
public static void main(String[] args) {
Authenticator.setDefault(new SimpleAuthenticator(ProxySettings.USER, ProxySettings.PASSWORD));
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost", ProxySettings.PROXY);
systemProperties.setProperty("http.proxyPort", ProxySettings.PORT);
try {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL("http://naoperturbe.itec.al.gov.br/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Referer", "");
conn.setInstanceFollowRedirects(true);
conn.setDoInput(true);
conn.setDoOutput(true);
String data = "username=08.504.728/0001-62&password=crediporto&this_is_the_login_form=1";
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(data);
dos.flush();
dos.close();
Object obj = conn.getContent();
CookieStore cookieJar = manager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
System.out.println(cookies);
String cookie = conn.getHeaderField("Set-Cookie");
cookie = cookie.substring(0, cookie.indexOf(";"));
System.out.println(cookie);
//System.exit(1);
URL url2 = new URL("http://naoperturbe.itec.al.gov.br/cadastro/lista_telefone_txt/");
conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
//conn.setRequestProperty("Cookie", "");
conn.setDoInput(true);
conn.setDoOutput(true);
System.out.println(conn.getContentType());
BufferedInputStream buf = new
BufferedInputStream(conn.getInputStream());
FileOutputStream out = new FileOutputStream("al.txt");
int i = 0;
byte[] bytesIn = new byte[1024];
while ((i = buf.read(bytesIn)) >= 0) {
out.write(bytesIn, 0, i);
}
buf.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
O script PHP que funciona:
<?php
require_once("lib.php");
echo "PROCON AL....";
$data = Array (
"dia" => date("d",strtotime("yesterday")),
"mes" => date("m",strtotime("yesterday")),
"ano" => date("Y",strtotime("yesterday"))
);
$user = "USER";
$pass = "PASS";
$diretorio = "download\\al\\";
$extensao = ".txt";
$nome_arquivo = $data["ano"] . $data["mes"] . $data["dia"] . $extensao;
$erro = false;
$arquivo = fopen($diretorio.$nome_arquivo, "w");
$url = "http://naoperturbe.itec.al.gov.br/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_login);
curl_setopt($ch, CURLOPT_PROXY, "prxwg.PROXY.brasil:3128");
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "USER:PASS");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=$user&password=$pass&this_is_the_login_form=1");
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
$url = "http://naoperturbe.itec.al.gov.br/cadastro/lista_telefone_txt/";
if(url_existe($url)) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FILE, $arquivo);
if($data = curl_exec($ch)) {
echo "OK!<br>";
}
} else {
echo "ARQUIVO NÃO ENCONTRADO!<br>";
$erro = true;
}
curl_close($ch);
fclose($arquivo);
if(true === $erro) {
unlink($diretorio.$nome_arquivo);
}
?>
Agradeço desde já!