(how) can I download an image using JSoup?

user1499731 picture user1499731 · Sep 17, 2012 · Viewed 28.5k times · Source

I already know where the image is, but for simplicity's sake I wanted to download the image using JSoup itself. (This is to simplify getting cookies, referrer, etc.)

This is what I have so far:

//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies).ignoreContentType(true).execute();

// output here
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new java.io.File(outputFolder + name));
//BufferedWriter out = new BufferedWriter(new FileWriter(outputFolder + name));
out.write(resultImageResponse.body());          // resultImageResponse.body() is where the image's contents are.
out.close();

Answer

user1499731 picture user1499731 · Sep 17, 2012

I didn't even finish writing the question before I found the answer via JSoup and a little experimentation.

//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies)
                                        .ignoreContentType(true).execute();

// output here
FileOutputStream out = (new FileOutputStream(new java.io.File(outputFolder + name)));
out.write(resultImageResponse.bodyAsBytes());  // resultImageResponse.body() is where the image's contents are.
out.close();