I am still practicing my java, and not so used to Writers, bufferedWriters etc. I have this method, which should make a get request to a server, get an image in return (filename is in the header) and save this image. This works except that image it saves is corrupted into been all black (image dimensions etc. is correct). Could anybody help me with what might cause this problem, and maybe suggest a solution?
private static void getAndSaveImage(String urlStem) throws Exception{
URL url = new URL(urlStem);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
IOUtils.copy(reader, writer);
}
I am currently investigating this thread answers: Getting Image from URL (Java)
I tried this as a potential solution (I know that I will get an .png-file), but then I get that the image file is empty afterwards.
private static void getAndSaveImage(String urlStem) throws Exception {
URL url = new URL(urlStem);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedImage image = ImageIO.read(con.getInputStream());
String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
File file = new File(fileName);
file.createNewFile();
ImageIO.write(image, ".png" , file);
}
I solved it with (modified from that thread):
public static void getAndSaveImage(String imageUrl) throws Exception {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
OutputStream os = new FileOutputStream(fileName);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
but an answer/suggestion on this thread was better.
I believe that this would be the implementation of the suggestion:
public static void saveImage(String imageUrl) throws Exception{
URL url = new URL(imageUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
FileUtils.copyURLToFile(url, file);
}
(sadly it seems I am doing two get requests for getting both the file name information in the header and the image itself)