Возобновить загрузку текстового файла в облако Google с помощью JSON API Cloud Storage в java, столкнувшись с проблемой доступа, запрещенной с кодом ошибки 403 - PullRequest
0 голосов
/ 22 ноября 2018

Я использую API возобновляемой загрузки API-интерфейса Cloud Storage JSON, как указано в приведенном ниже коде.

Я настроил свой json, связанный с учетными данными, в файле bash GOOGLE_APPLICATION_CREDENTIALS = {путь json}

Когда яя пытаюсь получить доступ к API Google. Я получаю сообщение о запрете доступа с кодом 403.

Нужно ли передавать подписанный URL-адрес в функцию загрузки?

Класс RetryHttpInitializerWrapper.не могу найти, поэтому я передал HttpRequestInitializer httpRequestInitializer = null;

У меня возникла проблема из-за URL-адреса запроса, в котором я уверен.

InputStreamContent mediaContent = new InputStreamContent(contentType, stream);
    mediaContent.setLength(mediaContent.getLength());
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(StorageScopes.all());
    }

    Storage client = StorageOptions.getDefaultInstance().getService();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    // custom HttpRequestInitializer for automatic retry upon failures.
    HttpRequestInitializer httpRequestInitializer = null;
    //HttpRequestInitializer httpRequestInitializer = new RetryHttpInitializerWrapper(credential);  
    GenericUrl requestUrl = new GenericUrl("https://www.googleapis.com/upload/storage/v1/b/"+bucket+"/o?uploadType=resumable&name="+name);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, httpTransport, httpRequestInitializer);
    uploader.setProgressListener(new CustomProgressListener());
    HttpResponse response = uploader.upload(requestUrl);
    if (!response.isSuccessStatusCode()) {
        throw  GoogleJsonResponseException.from(JSON_FACTORY, response);
    }

1 Ответ

0 голосов
/ 28 ноября 2018

Я исправил эту проблему с помощью заголовка аутентификации.Мы можем установить заголовок auth при вызове метода загрузки, как указано в коде.

Credentials credentials = GoogleCredentials.fromStream(new FileInputStream(CLIENTSECRETS_LOCATION));
    InputStreamContent mediaContent = new InputStreamContent(contentType, stream);
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    HttpRequestInitializer httpRequestInitializer = null;
    GenericUrl genericUrl = new GenericUrl(
            "https://www.googleapis.com/upload/storage/v1/b/" + bucket + "/o?uploadType=resumable&name=" + name);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, httpTransport, httpRequestInitializer);
    HttpHeaders requestHeaders = new HttpHeaders();
    credentials = ((GoogleCredentials) credentials).createScoped(StorageScopes.all());
    Map<String, List<String>> credentialHeaders = credentials.getRequestMetadata();
    if (credentialHeaders == null) {
        return;
    }
    for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) {
        String headerName = entry.getKey();
        List<String> requestValues = new ArrayList<>();
        requestValues.addAll(entry.getValue());
        requestHeaders.put(headerName, requestValues);
    }


HttpResponse response = uploader.setInitiationHeaders(requestHeaders).setDisableGZipContent(true)
                .upload(genericUrl);
...