-1

When I try to execute my code I get java.io.IOException: Server returned HTTP response code: 403 for URL, anyone knows what can I do?

I need a Java Class that downloads a file from the net but everytime I try to make it it downloads the HTML from the page or it doesn't download the file


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class URLReader {

    public static void copyURLToFile(URL url, File file) {

        try {
            InputStream input = url.openStream();
            if (file.exists()) {
                if (file.isDirectory())
                    throw new IOException("File '" + file + "' is a directory");

                if (!file.canWrite())
                    throw new IOException("File '" + file + "' cannot be written");
            } else {
                File parent = file.getParentFile();
                if ((parent != null) && (!parent.exists()) && (!parent.mkdirs())) {
                    throw new IOException("File '" + file + "' could not be created");
                }
            }

            FileOutputStream output = new FileOutputStream(file);

            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }

            input.close();
            output.close();

            System.out.println("File '" + file + "' downloaded successfully!");
        }
        catch(IOException ioEx) {
            ioEx.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        //URL pointing to the file
        String sUrl = "https://cdn-103.anonfiles.com/11HfTeD0uc/69e1a574-1630531823/main.exe";

        URL url = new URL(sUrl);

        //File where to be downloaded
        File file = new File("C:\\Users\\mader\\Desktop\\main.exe");

        URLReader.copyURLToFile(url, file);
    }

}





Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    Does this answer your question? [How to download and save a file from Internet using Java?](https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java) – vaibhavsahu Sep 02 '21 at 02:28
  • Is there even such a file at that address? – Scary Wombat Sep 02 '21 at 02:32

1 Answers1

1

Response code 403 indicates that the server refuses to authorize your request.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35