estou tentando fazer conforme passo a passo que se vem caminhando e estou com o seguinte código:
[code]public class NewClass {
public static void main(String[] args) throws IOException {
// Criando o cliente
DefaultHttpClient cliente = new DefaultHttpClient();
// Adicionando um sistema de redireção
cliente.setRedirectStrategy(new LaxRedirectStrategy());
// Mantendo a conexão sempre ativa
cliente.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
// Criando o container de cookies
CookieStore cookie = new BasicCookieStore();
// Criando o contexto de conexão
HttpContext contexto = new BasicHttpContext();
// Adicionando o coockie store no contexto de conexão
contexto.setAttribute(ClientContext.COOKIE_STORE, cookie);
// Criando o método de acesso
HttpGet requisição1 = new HttpGet("http://www.receita.fazenda.gov.br/PessoaJuridica/CNPJ/cnpjreva/Cnpjreva_Solicitacao2.asp");
// Resposta
HttpResponse resposta = cliente.execute(requisição1, contexto);
// Escrever informações
System.out.println("Status Line: " + resposta.getStatusLine());
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
// Buscando a entidade
HttpEntity entidade = resposta.getEntity();
// Transformando o conteúdo em uma string
String html = null;
try {
html = EntityUtils.toString(entidade);
} catch (IOException | ParseException exception) {
// Ocultado
}
// Busco o documento estruturado
HTMLDocument document = (new DocumentoHtml()).getHTMLDocument(html);
// Busco todos os elementos em forma de iterador
ElementIterator elementIterator = new ElementIterator(document);
// Crio o elemento que vai recepcionar
Element element;
//Crio o viewstate para receber um valor para o método post futuro
String viewstate = “”;
// Crio o imgcaptcha para receber um valor do link do captcha
String imgcaptcha = “”;
// Enquanto existir próximo elemento
while ((element = elementIterator.next()) != null) {
// Se for um input
if (element.getName().equals(HTML.Tag.INPUT.toString()) && ((String) element.getAttributes().getAttribute(HTML.Attribute.NAME)).equalsIgnoreCase(“viewstate”)) {
// Passo para a variável o valor do viewstate
viewstate = (String) element.getAttributes().getAttribute(HTML.Attribute.VALUE);
}
// Se for um img
if (element.getName().equals(HTML.Tag.IMG.toString()) && ((String) element.getAttributes().getAttribute(HTML.Attribute.ID)).equalsIgnoreCase(“imgcaptcha”)) {
// Passo para a variável o valor do imgcaptcha
imgcaptcha = “http://www.receita.fazenda.gov.br” + ((String) element.getAttributes().getAttribute(HTML.Attribute.SRC)).replaceAll(“amp”, “”);
}
}
// Escrever informações
System.out.println("Encoding: " + entidade.getContentEncoding());
System.out.println("Tamanho: " + entidade.getContentLength());
System.out.println("Tipo: " + entidade.getContentType());
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
// Baixar o stream
InputStream entrada = entidade.getContent();
// Cria um stream de leitura
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entrada, "LATIN1"));
// Cria o receptor de linha
String linha;
// Cria o acumulador
String acumulador = "";
// Para cada linha
while ((linha = bufferedReader.readLine()) != null) {
// Escreva
System.out.println(linha);
acumulador += "\n" + linha;
}
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
acumulador = acumulador.substring(acumulador.indexOf("/scripts/captcha/Telerik.Web.UI.WebResource.axd?"));
acumulador = acumulador.substring(0, acumulador.indexOf("'"));
System.out.println(acumulador.replaceAll("amp;", ""));
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
HttpGet requisição2 = new HttpGet("http://www.receita.fazenda.gov.br" + acumulador.replaceAll("amp;", "").replaceAll("cah", "rca"));
// Resposta
resposta = cliente.execute(requisição2, contexto);
// Escrever informações
System.out.println("Status Line: " + resposta.getStatusLine());
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
// Buscando a entidade
entidade = resposta.getEntity();
// Escrever informações
System.out.println("Encoding: " + entidade.getContentEncoding());
System.out.println("Tamanho: " + entidade.getContentLength());
System.out.println("Tipo: " + entidade.getContentType());
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
// Baixar o stream
entrada = entidade.getContent();
ByteArrayOutputStream out;
try (InputStream in = new BufferedInputStream(entrada)) {
out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
}
byte[] response = out.toByteArray();
try (FileOutputStream fos = new FileOutputStream("captcha.jpeg")) {
fos.write(response);
}
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
String captcha = JOptionPane.showInputDialog("Entre com o captcha:");
// Criando o método de acesso
HttpPost requisição3 = new HttpPost("http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/valida.asp");
// Lista de parâmetros
List<NameValuePair> nameValuePairs = new ArrayList<>();
// Adicionando os parâmetros
nameValuePairs.add(new BasicNameValuePair("origem", "comprovante"));
nameValuePairs.add(new BasicNameValuePair("search_type", "cnpj"));
nameValuePairs.add(new BasicNameValuePair("cnpj", "20589462000101"));
nameValuePairs.add(new BasicNameValuePair("captcha", captcha));
nameValuePairs.add(new BasicNameValuePair("captchaAudio", ""));
nameValuePairs.add(new BasicNameValuePair("submit1", "Consultar"));
nameValuePairs.add(new BasicNameValuePair("viewstate", viewstate));
// Encapsulando
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
// A adição dos parâmetros
requisição3.setEntity(urlEncodedFormEntity);
// Resposta
resposta = cliente.execute(requisição3, contexto);
// Escrever informações
System.out.println("Status Line: " + resposta.getStatusLine());
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
// Buscando a entidade
entidade = resposta.getEntity();
// Escrever informações
System.out.println("Encoding: " + entidade.getContentEncoding());
System.out.println("Tamanho: " + entidade.getContentLength());
System.out.println("Tipo: " + entidade.getContentType());
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
// Baixar o stream
entrada = entidade.getContent();
// Cria um stream de leitura
bufferedReader = new BufferedReader(new InputStreamReader(entrada));
// Para cada linha
while ((linha = bufferedReader.readLine()) != null) {
// Escreva
System.out.println(linha);
}
// Separador
System.out.println();
System.out.println("---------------------------------------------------------");
System.out.println();
}
}[/code]
está dando a seguinte exceção:
[code]
Status Line: HTTP/1.1 200 OK
Encoding: null
Tamanho: 8205
Tipo: Content-Type: text/html
Exception in thread “main” java.io.IOException: Attempted read from closed stream.
at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:167)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at NewClass.main(NewClass.java:142)
Java Result: 1[/code]
alguem pode me ajudar e me direcionar para dar o proximo passo?
minha linha 142 é:
while ((linha = bufferedReader.readLine()) != null) {