Home > OS >  How to download files from publicly available google drive URL using Java?
How to download files from publicly available google drive URL using Java?

Time:01-11

I have been trying to download files/whole directory from publicly available google drive link URL using Java. I am able to read files which are present in my google drive using google drive libraries but I am not able to understand how to pass google drive link URL.

Also, I tried to use typical method of downloading files from URL but it produced error java.io.IOException: Server returned HTTP response code: 400 for URL.

URL url;
URLConnection con;
DataInputStream dis;
FileOutputStream fos;
byte[] fileData;
try {
    url = new URL("https://drive.google.com/drive/folders/<some-alphanumeric-code>/<file-name>"); //File Location goes here
    con = url.openConnection(); // open the url connection.
    dis = new DataInputStream(con.getInputStream());
    fileData = new byte[con.getContentLength()];
    for (int q = 0; q < fileData.length; q  ) {
        fileData[q] = dis.readByte();
    }
    dis.close(); // close the data input stream
    fos = new FileOutputStream(new File("/Users/abhijeetkunwar/file.png")); //FILE Save Location goes here
    fos.write(fileData);  // write out the file we want to save.
    fos.close(); // close the output stream writer
}
catch(Exception m) {
   System.out.println(m);
}

Kindly suggest the solution please.

CodePudding user response:

The link you are using contains the folder id, the folder should also be readable by everyone.

In this instance you can use the files.list method from the Google drive api and access it using 'folderid' in parents which will return a list of all of the files within that folder.

For this to work the folder needs to be public to viewers which yours seem to be, after our conversation in chat.

  • Related