2016-09-09 5 views
0

Есть уже несколько человек, которые задавали вопросы по этому поводу, но я все еще не смог решить свою проблему.Google Drive 403 Запрещенная ошибка

Итак, я сделал gradle/java quickstart для печати имен и идентификаторов для 10 файлов в моем Googledrive. Это было хорошо, но я хочу написать сценарий java для загрузки файлов на моем диске, я вставил главную функцию ниже в свой java-файл.

public class DriveCommandLine { 

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

/** Directory to store user credentials for this application. */ 
private static final java.io.File DATA_STORE_DIR = new java.io.File(
     System.getProperty("user.home"), ".credentials/drive-java-quickstart"); 

/** Global instance of the {@link FileDataStoreFactory}. */ 
private static FileDataStoreFactory DATA_STORE_FACTORY; 

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

/** Global instance of the HTTP transport. */ 
private static HttpTransport HTTP_TRANSPORT; 

/** Global instance of the scopes required by this quickstart. 
* 
* If modifying these scopes, delete your previously saved credentials 
* at ~/.credentials/drive-java-quickstart 
*/ 
private static final List<String> SCOPES = 
     Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY); 

static { 
    try { 
     HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 
     DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); 
    } catch (Throwable t) { 
     t.printStackTrace(); 
     System.exit(1); 
    } 
} 

/** 
* Creates an authorized Credential object. 
* @return an authorized Credential object. 
* @throws IOException 
*/ 
public static Credential authorize() throws IOException { 
    // Load client secrets. 
    InputStream in = 
      DriveCommandLine.class.getResourceAsStream("/client_secret.json"); 
    GoogleClientSecrets clientSecrets = 
      GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); 

    // Build flow and trigger user authorization request. 
    GoogleAuthorizationCodeFlow flow = 
      new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) 
        .setDataStoreFactory(DATA_STORE_FACTORY) 
        .setAccessType("offline") 
        .build(); 
    Credential credential = new AuthorizationCodeInstalledApp(
      flow, new LocalServerReceiver()).authorize("user"); 
    System.out.println(
      "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); 
    return credential; 
} 

/** 
* Build and return an authorized Drive client service. 
* @return an authorized Drive client service 
* @throws IOException 
*/ 
public static Drive getDriveService() throws IOException { 
    Credential credential = authorize(); 
    return new Drive.Builder(
      HTTP_TRANSPORT, JSON_FACTORY, credential) 
      .setApplicationName(APPLICATION_NAME) 
      .build(); 
} 

public static void main(String[] args) throws IOException{ 

    //Insert a file 
    Drive service = getDriveService(); 
    File body = new File(); 
    body.setDescription("A test document"); 
    body.setMimeType("text/plain"); 

    java.io.File fileContent = new java.io.File("D:\\MyFiles\\nkonstantinidis\\Study\\IntelliJ_Shortcuts.txt"); 
    FileContent mediaContent = new FileContent("text/plain", fileContent); 

    File file = service.files().insert(body, mediaContent).execute(); 
    System.out.println("file ID: " + file.getId()); 
} 

}

И я получаю сообщение об ошибке показано ниже, когда я запускаю его

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden 
{ 
    "code" : 403, 
    "errors" : [ { 
    "domain" : "global", 
    "message" : "Insufficient Permission", 
    "reason" : "insufficientPermissions" 
    } ], 
    "message" : "Insufficient Permission" 
} 
     at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146) 
     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113) 
     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40) 
     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432) 
     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352) 
     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469) 
     at DriveCommandLine.main(DriveCommandLine.java:114) 

Я создал OAuth идентификатор клиента и поддержкой Google диск, но это по-прежнему делает это дело ,

Не могли бы вы помочь мне или даже лучше обратиться к учебнику для загрузки файлов на Google Drive, я довольно плохо разбираюсь в Java, так что несите меня.

Заранее спасибо.

ответ

1

Вы должны изменить СФЕРУ, используемую для подключения (Недостаточное разрешение сообщения) в соответствующий один

private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY); 

От DriveScope.class:

/** View and manage the files in your Google Drive. */ 
public static final String DRIVE = "https://www.googleapis.com/auth/drive"; 

/** View and manage its own configuration data in your Google Drive. */ 
public static final String DRIVE_APPDATA = "https://www.googleapis.com/auth/drive.appdata"; 

/** View and manage Google Drive files and folders that you have opened or created with this app. */ 
public static final String DRIVE_FILE = "https://www.googleapis.com/auth/drive.file"; 

/** View and manage metadata of files in your Google Drive. */ 
public static final String DRIVE_METADATA = "https://www.googleapis.com/auth/drive.metadata"; 

/** View metadata for files in your Google Drive. */ 
public static final String DRIVE_METADATA_READONLY = "https://www.googleapis.com/auth/drive.metadata.readonly"; 

/** View the photos, videos and albums in your Google Photos. */ 
public static final String DRIVE_PHOTOS_READONLY = "https://www.googleapis.com/auth/drive.photos.readonly"; 

/** View the files in your Google Drive. */ 
public static final String DRIVE_READONLY = "https://www.googleapis.com/auth/drive.readonly"; 

/** Modify your Google Apps Script scripts' behavior. */ 
public static final String DRIVE_SCRIPTS = "https://www.googleapis.com/auth/drive.scripts"; 

Не забудьте удалить сохраненные учетные данные (созданное приложением) после изменения SCOPE

+0

Спасибо миллион @marekk, я чувствую себя слепым, не могу поверить, что не видел этого, смотрел в него весь день. –

Смежные вопросы