Search code examples
javagoogle-search-consolegoogle-api-webmasters

Searchanalytics Query JAVA API v3 (Google WebMaster Tools)


I am trying to implement Google Webmasters Searchanalytics Query using using the Java API but i did not found any Java sample to use , in Google website here there is only Python samples for Searchanalytics Query , and they did not say that it's not available in Java API.

I found this class Webmasters.Searchanalytics.Query in the Java API which I assume that is equivalent to the Python function searchanalytics.query() but i did not found any implementation of it. My question if it is possible to query data from Google Search Console using the Java API?? if yes i wounder if there is someone who can provide a Java sample, something like the Python sample provided by Google here.

Thank you in advance.


Solution

  • I succeded to implement Webmasters.Searchanalytics.Query as follow

    first you need to create your QueryRequest using the SearchAnalyticsQueryRequest class example:

    private static SearchAnalyticsQueryRequest createSearchAnalyticsQueryRequest() {
            SearchAnalyticsQueryRequest searQueryRequest = new SearchAnalyticsQueryRequest();
            searQueryRequest.setStartDate("2016-04-10");
            searQueryRequest.setEndDate("2016-04-20");
            List<String> dimensions = new ArrayList<String>();
            dimensions.add("page");
            dimensions.add("query");
            dimensions.add("country");
            dimensions.add("device");
            dimensions.add("date");
            searQueryRequest.setDimensions(dimensions);
            return searQueryRequest;
        }
    

    then executing the query as follow :

    public static String Query(String site,
                SearchAnalyticsQueryRequest searQueryRequest) throws Exception {
    
            Webmasters.Searchanalytics.Query query = service.searchanalytics()
                    .query(site, searQueryRequest);
            SearchAnalyticsQueryResponse queryResponse = query.execute();
    
            return queryResponse.toPrettyString();
        }