Search code examples
javabucket

Google Cloud - Can't download from bucket


i'm with some problems to download files to the bucket using the google service of buckets. I spent some time searching on internet and could not have an answer.

Here is the code:

public static void downloadFileFromBucket(String stringUrl, String pathParaDownload) throws IOException {  
        URL somefile = new URL(stringUrl); 

        ReadableByteChannel rbc = null;
        try {
            rbc = Channels.newChannel(somefile.openStream());
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        FileOutputStream fos = new FileOutputStream(pathParaDownload);
        long start = System.currentTimeMillis();
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        long end = System.currentTimeMillis();
        System.out.println("Tempo de download: ");
        System.out.println(end-start);
        fos.close();
    } 

And here is the console log:

java.io.IOException: Server returned HTTP response code: 400 for URL: http://storage.googleapis.com/bucket-bruno/?key=AIzaSyBTOqMtlFD7KUsK7p9ObGlMBOJuQRyMxuM
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626)
    at java.net.URL.openStream(URL.java:1037)
    at projetoIntegracao.projetoIntegracao.DownloadBucket.downloadFileFromBucket(DownloadBucket.java:41)
    at projetoIntegracao.projetoIntegracao.DownloadBucket.main(DownloadBucket.java:33)

Edited: Here is the variable construction:

String stringUrl = "http://storage.googleapis.com/mybucketname/"+fileNameWithExtension+"?key="+apiKey;

Solution

  • Since HTTP 400 is invalid sintax, you need to verify your parameter "stringUrl", because the problem is over there.

    If you could post the code that generates this variable, it would be helpful.

    And have a look too if you have permissions on your bucket to download de file or use OAuth: https://developers.google.com/console/help/new/#generatingoauth2

    Edit: Ok, It seems you are not using OAuth to authenticate for download, so you need to let the file with open permission, have a look at the example:

    enter image description here

    But i recommend using OAuth 2.0