11

我已經成功實現了將數據從Google Big Query移至Google Storage的過程自動化。現在我需要以自動的方式將數據從Google Storage下載到我的環境中。使用Java從Google Storage下載文件

我想做一個正常的HTTP請求,但之前授權。所以,我的HTTP請求是

HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(authorize()); 
    GenericUrl url = new GenericUrl(uri); 
    HttpRequest request = requestFactory.buildGetRequest(url); 
    HttpResponse response = request.execute(); 
    String content = response.parseAsString(); 

我的授權碼是

/** Authorizes the installed application to access user's protected data. */ 
    private static Credential authorize() throws Exception 
    { 
     HttpTransport httpTransport = new NetHttpTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     // load client secrets 
     GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, 
       new InputStreamReader(BigQueryConsumer.class.getResourceAsStream("/secret.json"))); 

     // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore} 
     FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY)); 

     // set up authorization code flow 
     GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
       httpTransport, JSON_FACTORY, clientSecrets, 
       SCOPES).setDataStoreFactory(fileDataStoreFactory) 
       .build(); 
     // authorize 
     return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); 
    } 

凡以下常量是

  1. CREDENTIALS_DIRECTORY: 「.oauth的憑據」
  2. JSON_FACTORY:JacksonFactory。 getDefaultInstance()
  3. SCOPES:剛剛有字符串的列表「https://www.googleapis.com/auth/devstorage.full_control
  4. HTTP_TRANSPORT:新NetHttpTransport()

什麼我在身份驗證/授權過程丟失?我越來越

Exception in thread "main" com.google.api.client.http.HttpResponseException: 401 Unauthorized 
<HTML> 
<HEAD> 
<TITLE>Unauthorized</TITLE> 
</HEAD> 
<BODY BGCOLOR="#FFFFFF" TEXT="#000000"> 
<H1>Unauthorized</H1> 
<H2>Error 401</H2> 
</BODY> 
</HTML> 
+1

你可能也想嘗試一下。['gcloud-java'(http://googlecloudplatform.github.io/gcloud-java/),這裏的一些[示例代碼(HTTPS: //github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java)。 –

回答

5

對於其他尋找答案。要使用應用程序的默認憑據,您需要執行以下幾個步驟...您可以按照以下步驟操作,或查看此link

  1. 首先第一件事情:安裝谷歌雲存儲SDK
  2. 確保您可以從SDK運行命令。如果您沒有安裝python,則需要安裝python 2.7或更高版本以及pyopenssl ...
  3. 您需要通過運行 gcloud auth activate-service-account [Service account email] --key-fil e [.p12文件](編輯方括號中的值)。當您運行此應用程序時,您應該會收到一條消息,告知您已激活服務帳戶
  4. 您需要通過將 GOOGLE_APPLICATION_CREDENTIALS設置爲祕密的JSON路徑(從創建的服務帳戶下載的密碼)來設置SDK中的環境變量從開發者控制檯) CLOUDSDK_PYTHON_SITEPACKAGES爲1,並設置項目

命令來配置系統變量...

 
set GOOGLE_APPLICATION_CREDENTIALS "secret.json path" 
set CLOUDSDK_PYTHON_SITEPACKAGES 1 
gcloud config set project "your project name" 

後您進行驗證,並授權自己,你然後可以開始使用應用程序的默認憑據,因爲您已經正確設置了您的環境。

當您成功設置你的環境,你就可以進行身份​​驗證,並通過剛剛

 
     GoogleCredential credential = GoogleCredential.getApplicationDefault(); 

     if (credential.createScopedRequired()) { 
      credential = credential.createScoped(StorageScopes.all()); 
     } 

     HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
     storageService = new Storage.Builder(httpTransport, jsonFactory, credential) 
       .setApplicationName(applicationName).build(); 

得到默認的憑據,並使用HTTP GET來從你的谷歌存儲桶,即對象像下面

 
// Set up and execute a Google Cloud Storage request. 
       String uri = "https://storage.googleapis.com/" + URLEncoder.encode("[your bucket name here]", "UTF-8") + "/" + googleStorageFileName + "/" + fileName; 

       httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
       HttpRequestFactory requestFactory = httpTransport.createRequestFactory(
         credential); 
       GenericUrl url = new GenericUrl(uri); 

       HttpRequest request = requestFactory.buildGetRequest(url); 
       HttpResponse response = request.execute(); 
       String content = response.parseAsString(); 
       BufferedWriter writer = new BufferedWriter(new FileWriter(pathToSave + googleStorageFileName)); 
       writer.write(content); 
相關問題