2012-06-09 10 views
26

Estoy intentando descargar un archivo PDF con HttpClient. Puedo obtener el archivo, pero no estoy seguro de cómo convertir los bytes en un PDF y almacenarlo en algún lugar del sistemaCómo guardo un archivo descargado con HttpClient en una carpeta específica

Tengo el siguiente código, ¿Cómo puedo guardarlo como PDF?

public ???? getFile(String url) throws ClientProtocolException, IOException{ 

      HttpGet httpget = new HttpGet(url); 
      HttpResponse response = httpClient.execute(httpget); 
      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       long len = entity.getContentLength(); 
       InputStream inputStream = entity.getContent(); 
       // How do I write it? 
      } 

      return null; 
     } 

Respuesta

33
InputStream is = entity.getContent(); 
String filePath = "sample.txt"; 
FileOutputStream fos = new FileOutputStream(new File(filePath)); 
int inByte; 
while((inByte = is.read()) != -1) 
    fos.write(inByte); 
is.close(); 
fos.close(); 

EDIT:

también puede utilizar BufferedOutputStream y BufferedInputStream para descargar más rápido:

BufferedInputStream bis = new BufferedInputStream(entity.getContent()); 
String filePath = "sample.txt"; 
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); 
int inByte; 
while((inByte = bis.read()) != -1) bos.write(inByte); 
bis.close(); 
bos.close(); 
+6

HttpClient optimiza las operaciones de lectura internamente. No es necesario utilizar otra capa de almacenamiento en memoria intermedia – oleg

+0

No pude escribir directamente en esa ruta de archivo, tuve que usar 'Archivo archivo = nuevo archivo (context.getExternalFilesDir (Environment.DIRECTORY_DOWNLOADS)," filename.jpg ");' para escribiendo en el almacenamiento externo para que otras aplicaciones puedan ver mi aplicación – Aaron

1

Abrir una FileOutputStream y guardar los bytes de inputStream a ella.

+0

Lo que me confunde es que usted tiene un FileOutputStream ya está abierto en el método downloadAndSaveToFile, pero cuando se crea el objeto de archivo con la ruta completa, me sale un 'archivo no existe' error ... se puede mostrar ¿Qué código usamos para tomar este archivo que se descargó y guardarlo en una carpeta específica? –

+0

Disculpe, tuve un error tipográfico en mi camino. Como resultado, puedo especificar el objeto de archivo con la ruta completa deseada cuando la ruta es una ruta VÁLIDA. :-) –

21

Aquí es una solución sencilla utilizando IOUtils.copy():

File targetFile = new File("foo.pdf"); 

if (entity != null) { 
    InputStream inputStream = entity.getContent(); 
    OutputStream outputStream = new FileOutputStream(targetFile); 
    IOUtils.copy(inputStream, outputStream); 
    outputStream.close(); 
} 

return targetFile; 

IOUtils.copy() es excelente porque maneja el almacenamiento en búfer. Sin embargo, esta solución no es muy escalable:

  • no se puede especificar el nombre de archivo de destino y el directorio
  • es posible que desee almacenar los archivos de una manera diferente, por ejemplo, en una base de datos Los archivos no son necesarios en este escenario.

Mucho más escalable solución implica dos funciones:

public void downloadFile(String url, OutputStream target) throws ClientProtocolException, IOException{ 
    //... 
    if (entity != null) { 
    //... 
     InputStream inputStream = entity.getContent(); 
     IOUtils.copy(inputStream, target); 
    } 
} 

Y un método de ayuda:

public void downloadAndSaveToFile(String url, File targetFile) { 
    OutputStream outputStream = new FileOutputStream(targetFile); 
    downloadFile(url, outputStream); 
    outputStream.close(); 
} 
+0

¿Transmitirá esta secuencia el archivo o mantendrá todo el archivo en la memoria y luego lo guardará en el disco? –

26

Sólo para que conste que hay mejores maneras (más fácil) de hacer lo mismo

File myFile = new File("mystuff.bin"); 

CloseableHttpClient client = HttpClients.createDefault(); 
try (CloseableHttpResponse response = client.execute(new HttpGet("http://host/stuff"))) { 
    HttpEntity entity = response.getEntity(); 
    if (entity != null) { 
     try (FileOutputStream outstream = new FileOutputStream(myFile)) { 
      entity.writeTo(outstream); 
     } 
    } 
} 

O con la API fluida si a uno le gusta mejor

Request.Get("http://host/stuff").execute().saveContent(myFile); 
+2

Witch paquete ¿Necesito importar para 'Request.Get (" http: // host/cosas ") .execute(). SaveContent (myFile)' – badera

+0

En Maven necesita el artefacto 'org.apache.httpcomponents: fluent- hc' - el paquete de Java es 'org.apache.http.client.fluent.Request' –

Cuestiones relacionadas