javagoogle-analyticsgoogle-analytics-apigoogle-api-java-client

API source error when changing to Google Analytics Ga4


I changed Google Analytics to Ga4

The administrator is pulling statistics through the api and using it.

API is using v4, so I think it's compatible with ga4.

Follow the manual to connect to Google Cloud Platform + Analytics

I downloaded the json file and put in the viewId of Ga4.

However, permission errors continue to occur..

I'm asking because I don't know why...


    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 Please solve the problem


Solution

  • The Google Analytics Reporting API v4 API does not support Google Analytics 4, and it will throw 403 for all the GA4 properties as they are not supported.

    this is actually mentioned on the main page docs:

    https://developers.google.com/analytics/devguides/reporting/core/v4

    Note: This API does not support Google Analytics 4 (GA4) properties. Please use the Google Analytics Data API to access the new reporting features for GA4 properties.

    You need to use GA4 Data API for GA4 properties.