Ошибка «IOException: 400 Bad Request» для обновления подписей к видео на Youtube - PullRequest
0 голосов
/ 04 марта 2020

Мой код работает без проблем 9 месяцев go. Я ничего не изменил с тех пор. Мне нужно и пытался использовать свой код снова около 10 дней go. Я начал получать сообщения об ошибках с 10 дней go. Я прочитал почти все связанные ответы и перепробовал их все. Я обновил свои java (версия 1.8) и IDE (netbeans 11). Много других вещей. Я сделал небольшие улучшения. Но никто не решил мою проблему. Код ошибки следующий:

Mar 04, 2020 8:45:40 ÖS com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\V Masaustu\.oauth-credentials
Mar 04, 2020 8:45:40 ÖS com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\V Masaustu\.oauth-credentials
IOException: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Bad Request"
}
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Bad Request"
}
	at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
	at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
	at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
	at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
	at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
	at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
	at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
	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 com.google.api.services.samples.youtube.cmdline.data.CaptionsVideoUpload.main(CaptionsVideoUpload.java:109)
------------------------------------------------------------------------
BUILD SUCCESS

Мой код выглядит следующим образом. Это модифицированная версия образцов Google.

public class CaptionsVideoUpload {
    private static YouTube youtube;
    private static final String CAPTION_FILE_FORMAT = "*/*";
    private static final String SRT = "srt";
    public static void main(String[] args) {
        // This OAuth 2.0 access scope allows for full read/write access to the
        // authenticated user's account and requires requests to use an SSL connection.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
        
        String videoId = "i6nNoXDwerg";  
        String dizin = "F:\\Video_AltyaziKK\\Davut_Kaya";
        
        String dosyaYolu = System.getProperty("user.dir");
        dosyaYolu = dosyaYolu + "\\src\\main\\resources\\keys_davut_kaya.txt";        
        try {
            // Authorize the request.
            Credential credential = Auth.authorize(scopes, "captions");
            // This object is used to make YouTube Data API requests.
            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-captions-sample").build();
            YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet").setId(videoId);
            VideoListResponse listResponse = listVideosRequest.execute();

            List<Video> videoList = listResponse.getItems();
            if (videoList.isEmpty()) {
                System.out.println("Can't find a video with ID: " + videoId);
                return;
            }

            // Extract the snippet from the video resource.
            Video video = videoList.get(0);
            VideoSnippet snippet = video.getSnippet();
            List<String> tags = snippet.getTags();
            if (tags == null) {
                tags = new ArrayList<String>(1);
                snippet.setTags(tags);
            }

            File okunanDosya = new File(dosyaYolu);
            BufferedReader dosyaOkuyucu = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(okunanDosya), "UTF-8"));//new FileInputStream(okunanDosya), inputCharset))
            
            String sCurrentLine;
            ArrayList<String> tagsList = new ArrayList<String>();
            while ((sCurrentLine = dosyaOkuyucu.readLine()) != null) {
                tagsList.add(sCurrentLine);
            };
            int maxNumber = tagsList.size();
            int numberofWords = (int) maxNumber / 2;  //2 yerine 30
            for (int i = 0; i < numberofWords; i++) {
                Random rand = new Random();
                int randNum = rand.nextInt(maxNumber);
                tags.add(tagsList.get(randNum));
            }

            YouTube.Videos.Update updateVideosRequest = youtube.videos().update("snippet", video);
            Video videoResponse = updateVideosRequest.execute();

            // Print information from the updated resource.
            System.out.println("\n================== Returned Video ==================\n");
            System.out.println("  - Title: " + videoResponse.getSnippet().getTitle());
            System.out.println("  - Tags: " + videoResponse.getSnippet().getTags());
            
            File[] files = new File(dizin).listFiles();

            for (int i = 0; i <= files.length; i++) {//for (int i = 0; i <= 1; i++) {    //    

                String fileName = files[i].getName();
                String dilTuru = fileName.subSequence(0, 2).toString();
                if (!dilTuru.equals("ax")) {
                    String path = dizin + "\\" + fileName;
                    File captionFile = new File(path);
                    uploadCaption(videoId, dilTuru, fileName, captionFile);
                }
            }
            
        } catch (GoogleJsonResponseException e) {
            System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode()
                    + " : " + e.getDetails().getMessage());
            e.printStackTrace();
            
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("Throwable: " + t.getMessage());
            t.printStackTrace();
        }
    }

Я получаю сообщение об ошибке "VideoListResponse listResponse = listVideosRequest.execute ();" часть. Обратите внимание, что этот код вызывает следующий код.

public class Auth {

    /**
     * Define a global instance of the HTTP transport.
     */
    public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public static final JsonFactory JSON_FACTORY = new JacksonFactory();

    private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";

    /**
     * Authorizes the installed application to access user's protected data.
     *
     * @param scopes list of scopes needed to run youtube upload.
     * @param credentialDatastore name of the credential datastore to cache
     * OAuth tokens
     */
    public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

        FileInputStream fis=new FileInputStream(new File("C:\\Users\\V Masaustu\\Documents\\NetBeansProjects\\youtube-api-samples-master\\src\\main\\resources\\client_secrets.json"));
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(fis));

        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
                || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                    "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                    + "into src/main/resources/client_secrets.json");
            System.exit(1);
        }

        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
                .build();

        // Build the local server and bind it to port 8080
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
    }
}

Для меня очень важно исправить код. Большое спасибо.

...