Return error message if server doesn't respond for file download

I am using below code to download the file from Kaltura server. Can we identify, If we are getting the error from the server. So, for my case I am not getting error from the server and blank file is getting downloaded but I don't want to download the file. Instead, I want to return the error message.

        String s = "https://www.kaltura.com/p/588888/sp.....;   
        try {
            URL url = new URL(s);
           InputStream in = new BufferedInputStream(url.openStream());
            res.setContentType("application/octet-stream");
            res.setHeader("Cache-Control", "no-cache");
            res.setHeader("Content-Disposition","attachment;filename="+fileName);
            res.setStatus(200);
            OutputStream out = res.getOutputStream();
            byte[] buf = new byte[8192*2];
            while (in.read(buf) != -1)
            {
                out.write(buf);
            }
            out.flush();
            in.close();     
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

1 answer

  • answered 2018-05-16 06:58 RichardK

    I've used ImageIO to read image for this example. The easiest way would be to save this blank image which is shown on server to your computer, let's name it "blankImage.png". When you read image from url then you can compare if new image is the same as this one from your computer. You can't simply compare by equals, so you need another method: bufferedImagesAreEqual(). Then you know this is a blank image:

    BufferedImage blankImage = ImageIO.read(new File("C:/path/blankImage.png"));
            URL url = new URL("https://targetImageUrl");
            BufferedImage newImage = ImageIO.read(url);
    
            if (bufferedImagesAreEqual(blankImage, newImage)) {
                throw new Exception("Image is blank!");
            } else {
                //return your image;
            }
    
    private static boolean bufferedImagesAreEqual(BufferedImage img1, BufferedImage img2) {
            if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) {
                for (int x = 0; x < img1.getWidth(); x++) {
                    for (int y = 0; y < img1.getHeight(); y++) {
                        if (img1.getRGB(x, y) != img2.getRGB(x, y))
                            return false;
                    }
                }
            } else {
                return false;
            }
            return true;
        }