java 更改为Google Analytics Ga4时出现API源错误

jvidinwx  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(177)

我把Google Analytics改成了Ga4
管理员正在通过api提取统计数据并使用它。
API使用的是v4,所以我认为它与ga4兼容。
按照手册连接到Google Cloud Platform + Analytics
我下载了json文件,并放入Ga4的viewId。
但是,权限错误继续发生。
我问是因为我不知道为什么...

public static List<ReportRow> main(Map<String, Object> params) {
        List<ReportRow> list = null;
        try {
            AnalyticsReporting service = initializeAnalyticsReporting();

            GetReportsResponse response = getReport(service, params);
            list = printResponse(response);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /*  private static String absolutePath() {.
            try {
                Resource resource = new ClassPathResource("jinsil-dev-590e24c58176.json");
                return ResourceUtils.getFile("classpath:jinsil-dev-590e24c58176.json").getAbsolutePath();
                return resource.getURI().getPath().substring(1);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }*/

    /**
     * Initializes an Analytics Reporting API V4 service object.
     *
     * @return An authorized Analytics Reporting API V4 service object.
     * @throws IOException
     * @throws GeneralSecurityException
     */
    private static AnalyticsReporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(KEY_FILE_LOCATION))
            .createScoped(AnalyticsReportingScopes.all());

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

    /**
     * Queries the Analytics Reporting API V4.
     *
     * @param service An authorized Analytics Reporting API V4 service object.
     * @return GetReportResponse The Analytics Reporting API V4 response.
     * @throws IOException
     */
    private static GetReportsResponse getReport(AnalyticsReporting service, Map<String, Object> params)
        throws IOException {
        // Create the DateRange object.
        DateRange dateRange = new DateRange();
        dateRange.setStartDate((String) params.get("startDate"));
        dateRange.setEndDate((String) params.get("endDate"));

        String met = (String) params.get("metrics");
        String[] splited = met.split(",");
        Metric metrics[] = new Metric[3];

        Metric sessions = null;
        for (int i = 0; i < splited.length; i++) {
            sessions = new Metric().setExpression(splited[i]);
            metrics[i] = sessions;
        }
        // Create the Metrics object.

        Dimension pageTitle = new Dimension().setName((String) params.get("dimensions"));

        // Create the ReportRequest object.
        ReportRequest request = new ReportRequest().setViewId(VIEW_ID).setDateRanges(Arrays.asList(dateRange))
            .setMetrics(Arrays.asList(metrics)).setDimensions(Arrays.asList(pageTitle)).setIncludeEmptyRows(true);

        ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
        requests.add(request);

        // Create the GetReportsRequest object.
        GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);

        // Call the batchGet method.
        GetReportsResponse response = service.reports().batchGet(getReport).execute();

        // Return the response.
        return response;
    }

    /**
     * Parses and prints the Analytics Reporting API V4 response.
     *
     * @param response An Analytics Reporting API V4 response.
     * @return 
     */
    private static List<ReportRow> printResponse(GetReportsResponse response) {

        for (Report report : response.getReports()) {
            ColumnHeader header = report.getColumnHeader();
            List<ReportRow> rows = report.getData().getRows();

            if (rows == null) {
            }

            return rows;
        }

        return null;
    }
//error 

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
POST https://analyticsreporting.googleapis.com/v4/reports:batchGet
{
  "code": 403,
  "errors": [
    {
      "domain": "global",
      "message": "User does not have sufficient permissions for this profile.",
      "reason": "forbidden"
    }
  ],
  "message": "User does not have sufficient permissions for this profile.",
  "status": "PERMISSION_DENIED"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
    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$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1111)
    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 egovframework.dsc.statistics.web.HelloAnalyticsReporting.getReport(HelloAnalyticsReporting.java:126)
    at egovframework.dsc.statistics.web.HelloAnalyticsReporting.main(HelloAnalyticsReporting.java:50)
    at egovframework.dsc.statistics.web.statisticsController.selectVisitValueAjax(statisticsController.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:118)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at egovframework.com.cmm.filter.HTMLTagFilter.doFilter(HTMLTagFilter.java:36)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at egovframework.com.sec.security.filter.EgovSpringSecurityLoginFilter.doFilter(EgovSpringSecurityLoginFilter.java:387)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

pz请解决问题

czq61nw1

czq61nw11#

Google Analytics Reporting API v4 API***不支持Google Analytics 4***,并且它将为所有GA4属性抛出403,因为它们不受支持。
这实际上是在主页面文档中提到的:
https://developers.google.com/analytics/devguides/reporting/core/v4
注意:此API不支持Google Analytics 4(GA4)属性。请使用Google Analytics Data API访问GA4酒店的新报告功能。
您需要为GA4属性使用GA4 Data API

相关问题