0

Ich versuche, eine Datei in einen der Google Drive-Ordner meiner Firma hochzuladen, aber ich habe es nicht ohne Clienteingriff geschafft. Also, wenn ich dies:Google Drive API REST V2 Datei in Ordnerdatei einfügen nicht gefunden

package sample; 

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; 
import com.google.api.client.http.FileContent; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.services.drive.Drive; 
import com.google.api.services.drive.DriveScopes; 
import com.google.api.services.drive.model.File; 
import com.google.api.services.drive.model.ParentReference; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.Arrays; 

public class DriveCommandLine_srive 
{ 

    private static String CLIENT_ID = "myClientID.apps.googleusercontent.com"; 
    private static String CLIENT_SECRET = "myClientSecret"; 

    private static String REDIRECT_URI = "mything"; 

    public static void main(String[] args) throws IOException 
    { 
     HttpTransport httpTransport = new NetHttpTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)).setAccessType("online").setApprovalPrompt("auto").build(); 

     System.out.println("xxxxx : " + DriveScopes.DRIVE); 

     String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); 
     System.out.println("Please open the following URL in your browser then type the authorization code:"); 
     System.out.println(" " + url); 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String code = br.readLine(); 

     GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); 
     GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response); 

     // Create a new authorized API client 
     Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build(); 

     insertFile(service, "Test File Drive", "This is a test file","myCompanysFolderID" , "text/plain", "./data/document.txt"); 

     } 

    /** 
    * Insert new file. 
    * 
    * @param service Drive API service instance. 
    * @param title Title of the file to insert, including the extension. 
    * @param description Description of the file to insert. 
    * @param parentId Optional parent folder's ID. 
    * @param mimeType MIME type of the file to insert. 
    * @param filename Filename of the file to insert. 
    * @return Inserted file metadata if successful, {@code null} otherwise. 
    */ 
    private static File insertFile(Drive service, String title, String description, 
     String parentId, String mimeType, String filename) { 
     // File's metadata. 
     File body = new File(); 
     body.setTitle(title); 
     body.setDescription(description); 
     body.setMimeType(mimeType); 

     // Set the parent folder. 
     if (parentId != null && parentId.length() > 0) { 
     body.setParents(
      Arrays.asList(new ParentReference().setId(parentId))); 
     } 

     // File's content. 
     java.io.File fileContent = new java.io.File(filename); 
     FileContent mediaContent = new FileContent(mimeType, fileContent); 
     try { 
     File file = service.files().insert(body, mediaContent).execute(); 

     // Uncomment the following line to print the File ID. 
     System.out.println("File ID: " + file.getId()); 

     return file; 
     } catch (IOException e) { 
     System.out.println("An error occured: " + e); 
     return null; 
     } 
    } 

} 

ich verwalten, um erfolgreich die Datei in den Ordner des Unternehmens hochladen, aber ich habe es manuell zu genehmigen und der Code jedes Mal einfügen. Also, wie ich dies auf eine automatische Art und Weise machen möchte, habe ich die "Methode" der Autorisierung in eine geändert, die einen Schlüssel des Dienstkontos p12 verwendet, um den Klienten zu autorisieren. Dies ist der neue Code nach der Änderung:

package sample; 

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; 
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 
import com.google.api.client.http.FileContent; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.client.util.store.FileDataStoreFactory; 
import com.google.api.services.drive.Drive; 
import com.google.api.services.drive.DriveScopes; 
import com.google.api.services.drive.model.File; 
import com.google.api.services.drive.model.ParentReference; 


import java.io.IOException; 
import java.io.InputStream; 
import java.util.Arrays; 
import java.util.List; 

public class DriveCommandLine2 
{ 

    private static final String KEY_FILE_LOCATION = "data/myp12Key.p12"; 
    **//Note: this is the mail from a service account in my dev console, it is different from the OAuth client I use in the previous method.** 
    private static final String SERVICE_ACCOUNT_EMAIL ="[email protected]"; 

    /** Application name. */ 
    private static final String APPLICATION_NAME = 
     "Drive API Java Quickstart"; 

    /** Global instance of the JSON factory. */ 
    private static final JsonFactory JSON_FACTORY = 
     JacksonFactory.getDefaultInstance(); 

    public static void main(String[] args) throws Exception 
    { 
     //Drive service = getServiceManual(); 
     Drive service = initializeDrive(); 
     //insertFile(service, "Test File Drive", "This is a test file","myCompanyFolderID" , "text/plain", "./data/document.txt"); 
     insertFile(service, "Test File Drive", "This is a test file","" , "text/plain", "./data/document.txt"); 
     } 

    /** 
    * Insert new file. 
    * 
    * @param service Drive API service instance. 
    * @param title Title of the file to insert, including the extension. 
    * @param description Description of the file to insert. 
    * @param parentId Optional parent folder's ID. 
    * @param mimeType MIME type of the file to insert. 
    * @param filename Filename of the file to insert. 
    * @return Inserted file metadata if successful, {@code null} otherwise. 
    */ 
    private static File insertFile(Drive service, String title, String description, 
     String parentId, String mimeType, String filename) { 
     // File's metadata. 
     File body = new File(); 
     body.setTitle(title); 
     body.setDescription(description); 
     body.setMimeType(mimeType); 

     // Set the parent folder. 
     if (parentId != null && parentId.length() > 0) { 
     body.setParents(
      Arrays.asList(new ParentReference().setId(parentId))); 
     } 

     // File's content. 
     java.io.File fileContent = new java.io.File(filename); 
     FileContent mediaContent = new FileContent(mimeType, fileContent); 
     try { 
     File file = service.files().insert(body, mediaContent).execute(); 

     // Uncomment the following line to print the File ID. 
     System.out.println("File ID: " + file.getId()); 

     return file; 
     } catch (IOException e) { 
     System.out.println("An error occured: " + e); 
     return null; 
     } 
    } 


    ///////////////////// 
    ///NEW GOOGLE ANALYTICS AUTH 

    public static java.io.File convIs2File(InputStream inputStream, java.io.File file) 
    { 
     java.io.OutputStream outputStream = null; 

     try { 
      // write the inputStream to a FileOutputStream 
      outputStream = new java.io.FileOutputStream(file); 

      int read = 0; 
      byte[] bytes = new byte[1024]; 

      while ((read = inputStream.read(bytes)) != -1) { 
       outputStream.write(bytes, 0, read); 
      } 

      System.out.println("Done!"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (inputStream != null) { 
       try { 
        inputStream.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      if (outputStream != null) { 
       try { 
        // outputStream.flush(); 
        outputStream.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

      } 
     } 
     return file; 
    } 
    private static Drive initializeDrive() throws Exception { 
     // Initializes an authorized analytics service object. 

     // Construct a GoogleCredential object with the service account email 
     // and p12 file downloaded from the developer console. 
     HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
     InputStream is = DriveCommandLine2.class.getClassLoader().getResourceAsStream(KEY_FILE_LOCATION); 
     java.io.File f = java.io.File.createTempFile("myP12Key", ".p12"); 
     java.io.File f_used = convIs2File(is,f); 
     GoogleCredential credential = new GoogleCredential.Builder() 
       .setTransport(httpTransport) 
       .setJsonFactory(JSON_FACTORY) 
       .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
       .setServiceAccountPrivateKeyFromP12File(f_used) 
       .setServiceAccountScopes(DriveScopes.all()) 
       .build(); 

     // Construct the Analytics service object. 
     return new Drive.Builder(httpTransport, JSON_FACTORY, credential) 
       .setApplicationName(APPLICATION_NAME).build(); 
    } 


} 

Aber wenn ich diesen Code ausführen, bekomme ich folgende Fehlermeldung:

An error occured: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found 
{ 
    "code" : 404, 
    "errors" : [ { 
    "domain" : "global", 
    "location" : "file", 
    "locationType" : "other", 
    "message" : "File not found: myCompanyFolderID", 
    "reason" : "notFound" 
    } ], 
    "message" : "File not found: myCompanyFolderID" 
} 

Also, meine Vermutung ist, dass in der vorherige Genehmigung Art und Weise, ich bin Ich benutze meine Client_ID und Client_Secrets, um meine App zu autorisieren, Dinge in den Drive-Bereich meines Unternehmens einzufügen. Daher finde ich myCompanyFolder und kann die Datei erfolgreich einfügen. Bei der zweiten Methode versuche ich jedoch, die Datei in das Dienstkonto einzufügen Speicherplatz, auf den ich nicht zugreifen kann () Ich weiß das, denn wenn ich versuche, es in Drive's Root einzufügen, funktioniert es perfekt y, aber ich kann die Datei in meinem root nicht sehen).

Also am Ende, meine Frage ist, gibt es eine Möglichkeit, die Datei in meinem Unternehmen Laufwerksordner ohne manuelle Autorisierung zu tun? Das heißt, wie berechtige ich meine App, die Datei ohne menschliche Interaktion in das Laufwerk meines Unternehmens hochzuladen?

Ich denke, die client_secrets Weg wird nicht funktionieren, wie ich es zuvor versuchte und es fordert mich auf, es manuell zu tun, das erste Mal, wenn ich den Code ausführen. Da ich meinen Code von einer JAR-Datei auf einem Linux-Server aus führe, ist das überhaupt nicht praktikabel und funktioniert nicht für mich.

Danke!

Antwort

0

Die 404: File not found bedeutet, dass der Benutzer keinen Lesezugriff auf eine Datei hat oder die Datei nicht existiert.

Stellen Sie sicher, dass Sie bei der Anforderung von Dateimetadaten die korrekte access_token angeben. Versuchen Sie, den Autorisierungscode access_token neu zu generieren. Sie müssen authorize and authenticate Ihre Anfragen im Namen des Benutzers, ein Schlüssel und Ihre Client-ID wird nicht genug sein, um Benutzerdokument zugreifen.

Die Dokumentation schlägt vor, Benutzern mitzuteilen, dass sie keinen Lesezugriff auf die Datei haben oder dass die Datei nicht existiert. Sagen Sie ihnen, dass sie den Besitzer um Erlaubnis für die Datei bitten sollten.