[RESOLVIDO] Download de arquivos na net

3 respostas
M

Quero fazer o download do arquivo abaixo

http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_quina.zip

estou usando a API Apache Commons IO e o codigo abaixo

FileUtils.copyURLToFile(new URL("http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_quina.zip"), 
				  new File("quina.zip"));

e recebendo a mesagem de erro

Server redirected too many times (20)

nem o cURL ou o Wget conseguem pegar este arquivo,como posso fazer ? alguem tem alguma ideia ?

3 Respostas

A

Bom fiz um exemplo básico… espero que seja útil…

Entre no site --> http://hc.apache.org/downloads.cgi e faça o download do HttpClient 4.3.1 ou nesse link direto
http://ftp.unicamp.br/pub/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.3.1-bin.zip. Dentro do zip
haverá uma pasta lib…

Adicione os seguintes jars em seu projeto…

-httpclient-4.3.1.jar
-httpcore-4.3.jar
-commons-logging-1.1.3.jar

public class Download { 
    
    private HttpClient httpCliente;
    private HttpResponse httpResponse; 
    private HttpGet httpGet; 
    private HttpEntity httpEntity; 
    private ByteArrayOutputStream outBytes;
    private static final String LINK = "http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_quina.zip";    
    
    private ByteArrayOutputStream downloadZip(String link) {       
        httpCliente = new DefaultHttpClient(); 
        httpGet = new HttpGet(link); 
        outBytes = new ByteArrayOutputStream();      
        try{
            httpResponse = httpCliente.execute(httpGet);
            httpEntity = httpResponse.getEntity();
            if(httpEntity != null){                                
                httpEntity.writeTo(outBytes);     
                outBytes.close(); 
            }
        }        
        catch(IOException ex){}       
        return outBytes;
    }     
    
    public static void main(String[] args) { 
        File arq = new File("C:\\Users\\andy11x\\Desktop\\quina.zip");
        FileOutputStream fos = null;
        byte[] arqBytes = new Download().downloadZip(LINK).toByteArray();
        try{
            if(!arq.exists()){
                fos = new FileOutputStream(arq);
                fos.write(arqBytes);
                fos.close();
            }
        }
        catch(Exception ex){} //Gera FileNotFoundException e um IOException
    }    
}
M

Obrigado pela atenção ! vou executar o exemplo aqui e depois eu posto o resultado :slight_smile:

M

legal ! funcionou, só precisei modificar o seguinte

faça o import

import org.apache.http.impl.client.HttpClientBuilder;

e use este trecho

httpCliente = HttpClientBuilder.create().build();

no lugar de

httpCliente = new DefaultHttpClient();

pq o DefaultHttpClient está depreciado ! :slight_smile:

Criado 17 de janeiro de 2014
Ultima resposta 20 de jan. de 2014
Respostas 3
Participantes 2