11

Tôi đã tự động thành công quy trình di chuyển dữ liệu từ Google Big Query, tới Google Storage. Bây giờ tôi cũng cần phải tải dữ liệu từ Google Storage về môi trường của mình theo cách tự động.Tải xuống tệp từ Google Storage bằng cách sử dụng Java

Tôi đang cố thực hiện yêu cầu HTTP bình thường, nhưng cho phép trước đó. Vì vậy, yêu cầu HTTP của tôi là

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

Và mã uỷ quyền của tôi là

/** 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"); 
    } 

Trong trường hợp hằng số sau đây là

  1. CREDENTIALS_DIRECTORY: ".oauth-credentials"
  2. JSON_FACTORY: JacksonFactory. getDefaultInstance()
  3. SCOPES: Danh sách chuỗi chỉ có "https://www.googleapis.com/auth/devstorage.full_control"
  4. HTTP_TRANSPORT: mới NetHttpTransport()

tôi đang thiếu gì trong khi xác thực quá trình/ủy quyền? Tôi đang nhận được

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

Bạn cũng có thể muốn thử ['gcloud-java'] (http://googlecloudplatform.github.io/gcloud-java/), đây là một số [mã mẫu] (https: //github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java). –

Trả lời

5

Đối với những người khác tìm kiếm câu trả lời. Có một số bước mà bạn cần phải làm theo để sử dụng các thông tin đăng nhập mặc định của ứng dụng ... Bạn có thể làm theo các bước dưới đây, hoặc có một cái nhìn tại đây link.

  1. Trước tiên: cài đặt google đám mây lưu trữ SDK
  2. Hãy chắc chắn rằng bạn có thể chạy lệnh từ SDK. Nếu bạn không cài đặt python, bạn cần phải cài đặt python 2.7 hoặc cao hơn, và cũng pyopenssl ...
  3. Bạn cần xác thực từ bên trong SDK bằng cách chạy gcloud auth activate-service-account [Email tài khoản dịch vụ] --key-fil e [.p12 file] (Chỉnh sửa các giá trị trong dấu ngoặc vuông). Khi bạn chạy, bạn sẽ nhận được thông báo cho biết rằng bạn đã kích hoạt tài khoản dịch vụ của mình
  4. Bạn cần đặt biến môi trường từ SDK bằng cách đặt GOOGLE_APPLICATION_CREDENTIALS vào đường dẫn JSON của bí mật (tài khoản được tải xuống từ tài khoản dịch vụ được tạo từ các nhà phát triển console) CLOUDSDK_PYTHON_SITEPACKAGES đến 1, và cũng có thể thiết lập các dự án

lệnh để cấu hình các biến hệ thống ...

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

Sau khi bạn xác thực, và ủy quyền cho chính mình, bạn sau đó có thể bắt đầu sử dụng các thông tin đăng nhập mặc định của ứng dụng, do bạn đã thiết lập môi trường của mình đúng cách.

Khi bạn thành công thiết lập môi trường của bạn, bạn có thể sau đó xác thực và nhận được thông tin mặc định bằng cách chỉ

 
     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(); 

Và sử dụng HTTP GET để có được các đối tượng từ xô lưu trữ Google của bạn, ví dụ:giống như sau

 
// 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); 
Các vấn đề liên quan