Java: Descargar archivos desde un servidor remoto

August 24th, 2009 | by Seraphinux |

Problema

Deseas descargar un archivo desde un servidor remoto

Solución

Puedes utilizar la librería de Apache HttpClient

Código

import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 *
 * @author Seraphinux
 */
public class Main {
    public static void main(String[] args) {
        HttpClient miCliente = new HttpClient();
        PostMethod httpPost = new PostMethod();

        String enlace = "http://seraphinux.com/";
        String archivo = "lolcat.rar";
        try {

            httpPost.setURI(new URI(enlace + archivo));
            miCliente.executeMethod(httpPost);

            System.out.println("MSG: Status Line: "
                               + httpPost.getStatusLine());

            InputStream in = httpPost.getResponseBodyAsStream();

            System.out.println("MSG: Escribiendo el archivo "
                               + enlace);

            FileOutputStream fos = new FileOutputStream(new File(archivo));

            byte[] b = new byte[1024];
            int x = 0;
            while ((x = in.read(b)) > 0) {
                fos.write(b, 0, x);
            }

            in.close();
            fos.close();

        } catch (Exception ex) {
            System.err.println("ERR: " + ex.getMessage());
            System.err.println("ERR: Ocurrio un error al intentar "
                  + "conectarse a http://seraphinux.com/lolcat.rar");

            System.err.println("     Revisa tu conexion a Internet.");
            System.exit(-1);
        } finally {
            httpPost.releaseConnection();
        }

    }
}

Discusión

Haciendo uso de la librería HttpClient, es posible emular un navegador Web, y posteriormente descargar archivos desde un servidor remoto. La librería HttpClient nos permite acceder a formularios Web, realizar peticiones del tipo POST y GET, intercambio de datos a través de SSL y TLS.

Posts Relacionados

Tags: , ,

  1. 4 Responses to “Java: Descargar archivos desde un servidor remoto”

  2. By Nailuj on Aug 24, 2009 | Reply

    Gracias! :D ! aun no veo esto, pero archivaré el link mañana ‘juro’ que lo veo xD gracias :)
    $

  3. By Miguel Casallas on Aug 25, 2009 | Reply

    Hola
    Para decirte que tal vez esta línea se te ha duplicado:
    InputStream in = httpPost.getResponseBodyAsStream();
    in = httpPost.getResponseBodyAsStream();
    Aparte de eso, excelente dato, yo siempre he usado el método tradicional, lo había posteado hace algún tiempo en mi blog.
    http://sysdent.net23.net/2009/.....ando-java/
    http://sysdent.net23.net/2009/.....-gusanito/
    Por cierto de la de Gusanito tengo una nueva versión por subir que corrige unos problemas de formatos y bloqueo.

    Salu2.

  4. By Seraphinux on Aug 25, 2009 | Reply

    @Miguel Casallas

    Enterado, toda la razón, ya elimine la linea que esta de mas, en un rato le echo un ojo a tu blog.

    Saludos :D

  5. By Ajaxman on Sep 2, 2009 | Reply

    $wget -c http://www.sitio.com/archivo.rar
    Es mas mejor! :-)

Sorry, comments for this entry are closed at this time.