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 = ";   
        try {
            URL url = new URL(s);
           InputStream in = new BufferedInputStream(url.openStream());
            res.setHeader("Cache-Control", "no-cache");
            OutputStream out = res.getOutputStream();
            byte[] buf = new byte[8192*2];
            while ( != -1)
        } catch (Exception e) {
        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 = File("C:/path/blankImage.png"));
            URL url = new URL("https://targetImageUrl");
            BufferedImage newImage =;
            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;