最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ssl - PKIX path building failed: unable to find valid certification path to requested target when accessing Google APIs in Java

programmeradmin4浏览0评论

I am encountering the following error when attempting to access Google APIs in Java:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Here is the relevant part of the code:

package utilitymon;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;

import java.io.*;
import java.util.Arrays;
import java.util.List;

public class ReadGS {
    private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
    private static final java.io.File DATA_STORE_DIR = new java.io.File("src/main/resources/credentials");
    private static final String RESOURCE_PATH = "credentials.json";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final List<String> SCOPES = Arrays.asList(
            SheetsScopes.SPREADSHEETS,
            DriveScopes.DRIVE
    );
    private static Sheets sheetsService;
    private static FileDataStoreFactory DATA_STORE_FACTORY;
    private static HttpTransport HTTP_TRANSPORT;

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

    public static Credential authorize() throws Exception {
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
                JSON_FACTORY,
                new InputStreamReader(new FileInputStream(RESOURCE_PATH))
        );

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT,
                JSON_FACTORY,
                clientSecrets,
                SCOPES
        ).setDataStoreFactory(DATA_STORE_FACTORY).build();

        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    private static Drive getDriveService() throws Exception {
        Credential credential = authorize();
        return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static void exportSheetAsXLSX(String fileId, String exportPath) throws Exception {
        Drive driveService = getDriveService();
        try {
            File file = driveService.files().get(fileId).setFields("name, mimeType").execute();
            String fileName = file.getName();
            System.out.println("Exporting file: " + fileName);
            try (InputStream inputStream = driveService.files().export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").executeMediaAsInputStream();
                 FileOutputStream outputStream = new FileOutputStream(exportPath)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                System.out.println("Google Sheet exported as XLSX successfully to: " + exportPath);
            } catch (IOException e) {
                System.err.println("Error writing to file " + exportPath + ": " + e.getMessage());
                throw new IOException("Error exporting file " + fileId, e);
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("Google API Error while accessing file: " + fileId + " - " + e.getDetails());
            throw new Exception("Google API error during export", e);
        } catch (IOException e) {
            System.err.println("IO Error accessing file " + fileId + ": " + Arrays.toString(e.getStackTrace()));
            throw new IOException("Error accessing file " + fileId, e);
        } catch (Exception e) {
            System.err.println("Unexpected error occurred during export: " + e.getMessage());
            throw e;
        }
    }
}

And here are the dependencies I have in my pom.xml

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.33.0</version>
</dependency>
<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.33.1</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-sheets</artifactId>
    <version>v4-rev614-1.18.0-rc</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v3-rev197-1.25.0</version>
</dependency>

Problem: The error occurs when I try to access the Google Drive API to export a Google Sheet to XLSX:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This was working fine until recently, and now I'm getting the error. I've checked that my credentials are correct and that I have internet access, but I’m unsure why this error is occurring suddenly.

Steps I’ve already tried:

Updated Java and Maven dependencies. Checked my internet connection. Attempted to manually add the missing certificate to the Java truststore. Environment:

Java 11 Maven Google API Client Libraries (Google Drive, Google Sheets) Has anyone encountered this error before or have any suggestions for resolving it?

Any help would be appreciated!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论