tags:

views:

51

answers:

3

hi all, I'm using httpclient to download images from a webpage and I'm trying to save them to disk but not having much luck. I'm using the code below to fetch the image but not sure what needs to be done next to actually get it to disk, the fetch would be on a JPG or a PNG image path... thanks

HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetch.emptyCookieStore);

        HttpGet httpget = new HttpGet(pPage.imageSrc);
        HttpResponse response;
        response = httpClient.execute(httpget, localContext);

        Header[] headers = response.getAllHeaders();
        for(Header h: headers) {
          logger.info("HEADERS: "+h.getName()+ " value: "+h.getValue());
        }

        HttpEntity entity = response.getEntity();


        Header contentType = response.getFirstHeader("Content-Type");

        byte[] tmpFileData;

        if (entity != null) { 
          InputStream instream = entity.getContent();
          int l;
          tmpFileData = new byte[2048];
          while ((l = instream.read(tmpFileData)) != -1) {
          }
        }

tmpFileData should now hold the bytes of the jpg from the website.

+1  A: 

Have a look at FileOutputStream and its write method.

FileOutputStream out = new FileOutputStream("outputfilename");
out.write(tmpFileData);
Jeff
+1  A: 

Better use Apache commons-io, then you can just copy one InputStream to one OutputStream (FileOutputStream in your case).

Tassos Bassoukos
+1  A: 
if (entity != null) { 
    InputStream instream = entity.getContent();
    OutputStream outstream = new FileOutputStream("YourFile");
    org.apache.commons.io.IOUtils.copy(instream, outstream);
}
Taylor Leese
worked! thanks :)