Google Drive APIを使用したGoogle Driveからの直接ダウンロード

私のJavaで書かれたデスクトップアプリケーションは、Google Driveから公開ファイルをダウンロードしようとします。私が調べたところ、これはファイルの webContentLink を使って実装することができます(ユーザーの承認なしに公開ファイルをダウンロードする機能です)。

そのため、以下のコードは小さなファイルであれば動作します。

String webContentLink = aFile.getWebContentLink();
InputStream in = new URL(webContentLink).openStream();

なぜなら、この場合、グーグルウィルススキャンによる警告を伴うユーザー確認なしに、webContentLinkを介して直接ファイルをダウンロードすることができないからです。例を見てみましょう。ウェブコンテンツリンクを参照してください。

そこで質問なのですが、Google Driveから公開ファイルの内容をユーザーの承認なしに取得する方法はありますか?

ソリューション

2015年12月8日更新。 [Googleサポート][10]によると、

googledrive.com/host/ID

メソッドは2016年8月31日にオフになります。

---。

私はこの問題に遭遇しました。

トリックは、GoogleドライブフォルダーをWebホストのように扱うことです。

2015年4月1日更新

Googleドライブが変更され、ドライブへのリンクを誘導する簡単な方法があります。 私は以前の回答を参考にして以下に残しましたが、ここに更新された回答があります。

1。 Googleドライブにパブリックフォルダを作成します。

。 2。 このドライブを公に共有してください。

ここに画像の説明を入力してください

! 2。 そのフォルダーにいるときにアドレスバーからフォルダーUUIDを取得します

ここに画像の説明を入力してください。! 3。 このUUIDをこのURL

に入れます。 https://googledrive.com/host//。 4。 ファイルの場所に住所名を追加します。

https://googledrive.com/host//

----------。

< del> [Googleが意図する機能][2]< / del>
。 [新しいGoogleドライブリンク][3]。

公開されているドライブフォルダーの host URLを簡単に取得するだけです。 これを行うには、プレーンなHTMLファイルをアップロードしてプレビュー Googleドライブにアップロードし、ホストのURLを検索します。

手順は次のとおりです。

1。 Googleドライブにフォルダを作成します。

。 2。 このドライブを公に共有してください。

ここに画像の説明を入力してください

! 3。 単純なHTMLファイルをアップロードします。 追加のファイルを追加します(サブフォルダーはok)

ここに画像の説明を入力してください

! 4。 GoogleドライブでHTMLファイルを開いて「プレビュー」します

ここに画像の説明を入力してください

! 5。 このフォルダのURLアドレスを取得

ここに画像の説明を入力してください

! 6。 URLフォルダベースから直接リンクURLを作成します

ここに画像の説明を入力してください

! 7。 このURLを使用すると、大きなファイルを直接ダウンロードできます。

[編集]。

追加するのを忘れました。 サブフォルダーを使用してファイルを整理する場合は、URL階層で期待するようにフォルダー名を使用するだけです。

https://googledrive.com/host//images/my-image.png

----------。

私がやろうとしていたこと

Vagrantの仮想ボックスを使用してカスタムDebianイメージを作成しました。 この「.box」ファイルを同僚と共有して、直接リンクをVagrantfileに配置できるようにしたかったのです。

結局、実際のファイルへの直接リンクが必要でした。

Googleドライブの問題

gdocs2directツールのようなものを使用するか、自分でリンクを作成して、ファイル権限を公開して直接アクセスリンクを作成/生成する場合:

https://docs.google.com/uc?export = download& id =< your file id>

Cookieベースの検証コードとプロンプト「Googleはこのファイルをスキャンできませんでした」プロンプトが表示されます。これは、 wget やVagrantfile構成などでは機能しません。

生成するコードは、GETクエリ変数 を追加する単純なコードです。..& confirm =###を文字列に追加しますが、ユーザー固有であるため、他のクエリ変数をコピー/貼り付けすることはできません。

ただし、上記の「Webページホスティング」メソッドを使用すると、そのプロンプトを回避できます。

それが役に立てば幸いです。!

[10]:https://support.google.com/drive/answer/2881970?hl = en。

解説 (17)

「このファイルでウイルスをチェックできない」インターメッツォページに直面した場合、ダウンロードはそれほど簡単ではありません。

基本的に、最初に通常のダウンロードリンクをダウンロードする必要がありますが、[とにかくダウンロード]ページにリダイレクトされます。 この最初のリクエストからCookieを保存し、「とにかくダウンロード」ボタンで指されたリンクを見つけてから、このリンクを使用してファイルをダウンロードする必要がありますが、最初のリクエストから取得したCookieを再利用します。

CURLを使用したダウンロードプロセスのbashバリアントは次のとおりです。

curl -c /tmp/cookies "https://drive.google.com/uc?export=download&id=DOCUMENT_ID" > /tmp/intermezzo.html
curl -L -b /tmp/cookies "https://drive.google.com$(cat /tmp/intermezzo.html | grep -Po 'uc-download-link" [^>]* href="\K[^"]*' | sed 's/\&/\&/g')" > FINAL_DOWNLOADED_FILENAME

注意:

*この手順は、Googleが変更された後、おそらく機能しなくなります。

  • grepコマンドはPerl構文( -P)と \ K "operator"を使用します。これは、基本的に "一致した結果の\ Kの前に何も含めないことを意味します。 grepのどのバージョンがこれらのオプションを導入したかはわかりませんが、古代バージョンまたは非Ubuntuバージョンにはおそらくありません。
  • Javaソリューションはほぼ同じですが、Cookieを処理できるHTTPSライブラリと、いくつかの優れたテキスト解析ライブラリを使用します。
解説 (4)

これは古い質問であることは知っていますが、調査の結果、この問題の解決策を見つけることができなかったため、何が効果的だったかを共有しています。

私のプロジェクトの1つにこのC#コードを書きました。 プログラムでスキャンウイルス警告をバイパスできます。 コードはおそらくJavaに変換できます。

using System;
using System.IO;
using System.Net;

public static class FileDownloader
{
    private const string GOOGLE_DRIVE_DOMAIN = "drive.google.com";
    private const string GOOGLE_DRIVE_DOMAIN2 = "https://drive.google.com";

    // Normal example: FileDownloader.DownloadFileFromURLToPath( "http://example.com/file/download/link", @"C:\file.txt" );
    // Drive example: FileDownloader.DownloadFileFromURLToPath( "http://drive.google.com/file/d/FILEID/view?usp=sharing", @"C:\file.txt" );
    public static FileInfo DownloadFileFromURLToPath( string url, string path )
    {
        if( url.StartsWith( GOOGLE_DRIVE_DOMAIN ) || url.StartsWith( GOOGLE_DRIVE_DOMAIN2 ) )
            return DownloadGoogleDriveFileFromURLToPath( url, path );
        else
            return DownloadFileFromURLToPath( url, path, null );
    }

    private static FileInfo DownloadFileFromURLToPath( string url, string path, WebClient webClient )
    {
        try
        {
            if( webClient == null )
            {
                using( webClient = new WebClient() )
                {
                    webClient.DownloadFile( url, path );
                    return new FileInfo( path );
                }
            }
            else
            {
                webClient.DownloadFile( url, path );
                return new FileInfo( path );
            }
        }
        catch( WebException )
        {
            return null;
        }
    }

    // Downloading large files from Google Drive prompts a warning screen and
    // requires manual confirmation. Consider that case and try to confirm the download automatically
    // if warning prompt occurs
    private static FileInfo DownloadGoogleDriveFileFromURLToPath( string url, string path )
    {
        // You can comment the statement below if the provided url is guaranteed to be in the following format:
        // https://drive.google.com/uc?id=FILEID&export=download
        url = GetGoogleDriveDownloadLinkFromUrl( url );

        using( CookieAwareWebClient webClient = new CookieAwareWebClient() )
        {
            FileInfo downloadedFile;

            // Sometimes Drive returns an NID cookie instead of a download_warning cookie at first attempt,
            // but works in the second attempt
            for( int i = 0; i < 2; i++ )
            {
                downloadedFile = DownloadFileFromURLToPath( url, path, webClient );
                if( downloadedFile == null )
                    return null;

                // Confirmation page is around 50KB, shouldn't be larger than 60KB
                if( downloadedFile.Length > 60000 )
                    return downloadedFile;

                // Downloaded file might be the confirmation page, check it
                string content;
                using( var reader = downloadedFile.OpenText() )
                {
                    // Confirmation page starts with , which can be preceeded by a newline
                    char[] header = new char[20];
                    int readCount = reader.ReadBlock( header, 0, 20 );
                    if( readCount < 20 || !( new string( header ).Contains( "" ) ) )
                        return downloadedFile;

                    content = reader.ReadToEnd();
                }

                int linkIndex = content.LastIndexOf( "href=\"/uc?" );
                if( linkIndex < 0 )
                    return downloadedFile;

                linkIndex += 6;
                int linkEnd = content.IndexOf( '"', linkIndex );
                if( linkEnd < 0 )
                    return downloadedFile;

                url = "https://drive.google.com" + content.Substring( linkIndex, linkEnd - linkIndex ).Replace( "&", "&" );
            }

            downloadedFile = DownloadFileFromURLToPath( url, path, webClient );

            return downloadedFile;
        }
    }

    // Handles 3 kinds of links (they can be preceeded by https://):
    // - drive.google.com/open?id=FILEID
    // - drive.google.com/file/d/FILEID/view?usp=sharing
    // - drive.google.com/uc?id=FILEID&export=download
    public static string GetGoogleDriveDownloadLinkFromUrl( string url )
    {
        int index = url.IndexOf( "id=" );
        int closingIndex;
        if( index > 0 )
        {
            index += 3;
            closingIndex = url.IndexOf( '&', index );
            if( closingIndex < 0 )
                closingIndex = url.Length;
        }
        else
        {
            index = url.IndexOf( "file/d/" );
            if( index < 0 ) // url is not in any of the supported forms
                return string.Empty;

            index += 7;

            closingIndex = url.IndexOf( '/', index );
            if( closingIndex < 0 )
            {
                closingIndex = url.IndexOf( '?', index );
                if( closingIndex < 0 )
                    closingIndex = url.Length;
            }
        }

        return string.Format( "https://drive.google.com/uc?id={0}&export=download", url.Substring( index, closingIndex - index ) );
    }
}

// Web client used for Google Drive
public class CookieAwareWebClient : WebClient
{
    private class CookieContainer
    {
        Dictionary _cookies;

        public string this[Uri url]
        {
            get
            {
                string cookie;
                if( _cookies.TryGetValue( url.Host, out cookie ) )
                    return cookie;

                return null;
            }
            set
            {
                _cookies[url.Host] = value;
            }
        }

        public CookieContainer()
        {
            _cookies = new Dictionary();
        }
    }

    private CookieContainer cookies;

    public CookieAwareWebClient() : base()
    {
        cookies = new CookieContainer();
    }

    protected override WebRequest GetWebRequest( Uri address )
    {
        WebRequest request = base.GetWebRequest( address );

        if( request is HttpWebRequest )
        {
            string cookie = cookies[address];
            if( cookie != null )
                ( (HttpWebRequest) request ).Headers.Set( "cookie", cookie );
        }

        return request;
    }

    protected override WebResponse GetWebResponse( WebRequest request, IAsyncResult result )
    {
        WebResponse response = base.GetWebResponse( request, result );

        string[] cookies = response.Headers.GetValues( "Set-Cookie" );
        if( cookies != null && cookies.Length > 0 )
        {
            string cookie = "";
            foreach( string c in cookies )
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }

    protected override WebResponse GetWebResponse( WebRequest request )
    {
        WebResponse response = base.GetWebResponse( request );

        string[] cookies = response.Headers.GetValues( "Set-Cookie" );
        if( cookies != null && cookies.Length > 0 )
        {
            string cookie = "";
            foreach( string c in cookies )
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }
}
解説 (1)

これは2015年5月19日をもって再度更新されるようです:

どのように機能させたか:

jmbertucciの最近更新された回答と同様に、フォルダをすべての人に公開します。 これは以前よりも少し複雑です。[詳細]をクリックして、フォルダを[オン]-[Web上のパブリック]に変更する必要があります。"。

以前と同じようにフォルダUUIDを見つけます。フォルダーに移動して、アドレスバーでUUIDを見つけます。

https://drive.google.com/drive/folders/

次に向かいます。

https://googledrive.com/host/

巨大なサブドメインを持つインデックスタイプのページにリダイレクトされますが、フォルダ内のファイルを表示できるはずです。 次に、右クリックして、必要なファイルへのリンクを保存できます(この直接リンクにも「googledrive.com」の大きなサブドメインがあることに気づきました)。 「ウィート」で私のために素晴らしい働きをしました。

これは、他の共有フォルダでも動作するようです。

例えば.、。

https://drive.google.com/folderview?id = 0B7l10Bj_LprhQnpSRkpGMGV2eE0& usp =共有。

にマップします。

https://googledrive.com/host/0B7l10Bj_LprhQnpSRkpGMGV2eE0

また、右クリックすると、これらのファイルへの直接リンクを保存できます。

解説 (2)

#ケース1:小さいサイズのファイルをダウンロードします。

-URLはhttps://drive.google.com/uc形式で使用できます?export = download& id = FILE_ID、そしてファイルのinputstreamを直接取得できます。

#ケース2:大きなサイズのファイルをダウンロードします。

-ウイルススキャンアラートページの壁が貼り付けられました。 html dom要素を解析することで、[とにかくダウンロード]ボタンの下に確認コードを含むリンクを取得しようとしましたが、機能しませんでした。 Cookieまたはセッション情報が必要になる場合があります。 ここに画像の説明を入力してください

ソリューション:

-最後に、上記の2つのケースの解決策を見つけました。 Jsonを取得するには、接続ステップに「httpConnection.setDoOutput(true)」を配置するだけです。

`)]} '{"処分": "SCAN_CLEAN"、。
"downloadUrl": "http:www。.."、。
"fileName": "exam_list_json.txt"、 "scanResult": "OK"、 "sizeBytes":2392} `。

次に、任意のJsonパーサーを使用して、ダウンロードUrl、fileName、sizeBytesを読み取ることができます。

-フォロースニペットを参照できます。

    private InputStream gConnect(String remoteFile)はIOException {を投げます。
        URL url = new URL(remoteFile);。
        URLConnection接続= url.openConnection();。
        if(HttpURLConnectionの接続インスタンス){。
            HttpURLConnection httpConnection =(HttpURLConnection)接続;。
            connection.setAllowUserInteraction(false);。
            httpConnection.setInstanceFollowRedirects(true); 
            httpConnection.setRequestProperty( "User-Agent"、 "Mozilla / 4.0(compatible; MSIE 6.0; Windows 2000)");。
            httpConnection.setDoOutput(true);。
                    httpConnection.setRequestMethod( "GET"); .
            httpConnection.connect();。

            int reqCode = httpConnection.getResponseCode();。

            if(reqCode == HttpURLConnection.HTTP_OK){。
                InputStreamは= httpConnection.getInputStream();です。
                Map< String、List< String>>マップ= httpConnection.getHeaderFields();。
                List< String>値= map.get( "content-type");。
                if(値。 != null&&  !values.isEmpty()){。
                    文字列type = values.get(0);。

                    if(type.contains( "text / html")){。
                        文字列cookie = httpConnection.getHeaderField( "Set-Cookie");。
                        文字列temp = Constants.getPath(mContext、Constants.PATH_TEMP)+ "/temp.html";。
                        if(saveGHtmlFile(is、temp)){。
                            文字列href = getRealUrl(temp);。
                            if(href。 != null){。
                                return parseUrl(href、cookie);。
                            }。
                        }。

                    } else if(type.contains( "application / json")){。
                        文字列temp = Constants.getPath(mContext、Constants.PATH_TEMP)+ "/temp.txt";。
                        if(saveGJsonFile(is、temp)){。
                            FileDataSetデータ= JsonReaderHelper.readFileDataset(新しいファイル(temp));。
                            if(data.getPath()。 != null){。
                                return parseUrl(data.getPath());。
                            }。
                        }。
                    }。
                }。
                戻りです。
            }。
        }。
        nullを返します。
    }。

そして。

   public static FileDataSet readFileDataset(File file) throws IOException{
        FileInputStream is = new FileInputStream(file);
        JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));

        reader.beginObject();
        FileDataSet rs = new FileDataSet();
        while(reader.hasNext()){
            String name = reader.nextName();
            if(name.equals("downloadUrl")){
                rs.setPath(reader.nextString());
            } else if(name.equals("fileName")){
                rs.setName(reader.nextString());
            } else if(name.equals("sizeBytes")){
                rs.setSize(reader.nextLong());
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        return rs;

    }
解説 (0)

https://github.com/google/skicka

このコマンドラインツールを使用して、Googleドライブからファイルをダウンロードしました。 [スタートの取得]セクションの手順に従ってください。Googleドライブから数分でファイルをダウンロードする必要があります。

解説 (0)

サービスアカウントを利用するとよいかもしれません。

解説 (0)

プログラム的に(ユーザーがブラウザーで開くためのリンクを提供するのとは対照的に)GoogleドライブAPIからファイルをダウンロードする場合は、文書化されているように、「webContentLink」の代わりにファイルの「downloadUrl」を使用することをお勧めしますここ:https://developers.google.com/drive/web/manage-downloads

解説 (0)

リンクからダウンロードし、確認リンクを取得するページをスクレイピングし、それをダウンロードすることを検討します。

もしあなたが "download anyway" URL を見ると、そこには余分な confirm クエリーパラメーターがあり、一見ランダムに生成されたトークンが付いているように見えます。それはランダムなので...そしておそらくあなたはそれを自分で生成する方法を見つけたいとは思わないので、サイトの仕組みについて何も知らなくても、スクレイピングが最も簡単な方法かもしれません。

いろいろなシナリオを考える必要がありそうです。

解説 (1)

https://drive.google.com/uc?export=download&id=FILE_ID FILE_IDをファイルIDに置き換えてください。

ファイルIDがわからない場合は、こちらの記事Article LINKを参照してください。

解説 (1)

javascriptを作成するだけで、リンクを自動的にキャプチャし、[tampermonkey][2]を使用してタブをダウンロードして閉じます。

// ==UserScript==
// @name         Bypass Google drive virus scan
// @namespace    SmartManoj
// @version      0.1
// @description  Quickly get the download link
// @author       SmartManoj
// @match        https://drive.google.com/uc?id=*&export=download*
// @grant        none
// ==/UserScript==

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function demo() {
        await sleep(5000);
        window.close();
    }

    (function() {
        location.replace(document.getElementById("uc-download-link").href);
        demo();
    })();

同様に、URLのHTMLソースを取得して、javaでダウンロードできます。

[2]:https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkebhmkfjojejmpbldmpobfkfo?utm_source = chrome-app-launcher-info-dialog。

解説 (0)