1

源代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.Analytics.Data.Ga.Get;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.GaData.ColumnHeaders;
import com.google.api.services.analytics.model.Profile;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Segment;
import com.google.api.services.analytics.model.Segments;

/**
* This class displays an example of a client application using the Google API
* to access the Google Analytics data
* 
*
* 
*/
@SuppressWarnings("deprecation")
public class GoogleAnalyticsExample {
private static final String SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
private static final String REDIRECT_URL = "urn:ietf:wg:oauth:2.0:oob";
private static final HttpTransport netHttpTransport = new NetHttpTransport();
private static final JacksonFactory jacksonFactory = new JacksonFactory();
private static final String APPLICATION_NAME = "familys";
// FILL THESE IN WITH YOUR VALUES FROM THE API CONSOLE
private static final String CLIENT_ID = "XXXXXX";
private static final String CLIENT_SECRET = "XXXXXX";

public static void main(String args[]) throws HttpResponseException,
        IOException {
    // Generate the URL to send the user to grant access.
    GoogleCredential credential = null;
    String authorizationUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,
            REDIRECT_URL, SCOPE).build();
    System.out.println("Go to the following link in your browser:");
    System.out.println(authorizationUrl);

    // Get authorization code from user.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is the authorization code?");
    String authorizationCode = null;
    try {
        authorizationCode = in.readLine();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    // Use the authorisation code to get an access token
    AccessTokenResponse response = null;
    try {
        response = new GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant(
                netHttpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET,
                authorizationCode, REDIRECT_URL).execute();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    // Use the access token to get a new GoogleAccessProtectedResource.
    GoogleAccessProtectedResource googleAccessProtectedResource = new GoogleAccessProtectedResource(
            response.accessToken, netHttpTransport, jacksonFactory,
            CLIENT_ID, CLIENT_SECRET, response.refreshToken);

    // Instantiating a Service Object
//      Analytics analytics = Analytics
//              .Builder(netHttpTransport, jacksonFactory)
//              .setHttpRequestInitializer(googleAccessProtectedResource)
//              .setApplicationName(APPLICATION_NAME).build();
    Analytics analytics = new Analytics.Builder(netHttpTransport, jacksonFactory, credential)
    .setHttpRequestInitializer(googleAccessProtectedResource).setApplicationName(APPLICATION_NAME).build();
    analytics.getApplicationName();
    System.out.println("Application Name: "
            + analytics.getApplicationName());
    // Get profile details
    Profiles profiles = analytics.management().profiles()
            .list("~all", "~all").execute();
    displayProfiles(profiles, analytics);

    // Get the segment details
    Segments segments = analytics.management().segments().list().execute();
    displaySegments(segments);

}

/**
 * displayProfiles gives all the profile info for this property
 * @param profiles
 * @param analytics
 */
public static void displayProfiles(Profiles profiles, Analytics analytics) {
    for (Profile profile : profiles.getItems()) {
        System.out.println("Account ID: " + profile.getAccountId());
        System.out
                .println("Web Property ID: " + profile.getWebPropertyId());
        System.out.println("Web Property Internal ID: "
                + profile.getInternalWebPropertyId());
        System.out.println("Profile ID: " + profile.getId());
        System.out.println("Profile Name: " + profile.getName());

        System.out.println("Profile defaultPage: "
                + profile.getDefaultPage());
        System.out.println("Profile Exclude Query Parameters: "
                + profile.getExcludeQueryParameters());
        System.out.println("Profile Site Search Query Parameters: "
                + profile.getSiteSearchQueryParameters());
        System.out.println("Profile Site Search Category Parameters: "
                + profile.getSiteSearchCategoryParameters());

        System.out.println("Profile Currency: " + profile.getCurrency());
        System.out.println("Profile Timezone: " + profile.getTimezone());
        System.out.println("Profile Updated: " + profile.getUpdated());
        System.out.println("Profile Created: " + profile.getCreated());

        try {
            /**
             * The get method follows the builder pattern, where all
             * required parameters are passed to the get method and all
             * optional parameters can be set through specific setter
             * methods.
             */
            // Possible to Build API Query with various criteria as below
            Get apiQuery = analytics.data().ga()
                    .get("ga:" + profile.getId(), // Table ID =
                                                    // "ga"+ProfileID
                            "2013-03-21", // Start date
                            "2013-05-04", // End date
                            "ga:visits"); // Metrics
            apiQuery.setDimensions("ga:source,ga:medium");
            apiQuery.setFilters("ga:medium==referral");
            apiQuery.setSort("-ga:visits");
            apiQuery.setSegment("gaid::-11");
            apiQuery.setMaxResults(100);

            // Make Data Request
            GaData gaData = apiQuery.execute();
            if (profile.getId() != null) {
                retrieveData(gaData);
            }

        } catch (IOException e) {
            System.out.println("Inside displayProfile method");
            e.printStackTrace();
        }
    }
}

/**
 * retrieveData() gets the Google Analytics user data 
 * @param gaData
 */
public static void retrieveData(GaData gaData) {
    // Get Row Data
    if (gaData.getTotalResults() > 0) {
        // Get the column headers
        for (ColumnHeaders header : gaData.getColumnHeaders()) {
            System.out.format("%-20s",
                    header.getName() + '(' + header.getDataType() + ')');
        }
        System.out.println();
        // Print the rows of data.
        for (List<String> rowValues : gaData.getRows()) {
            for (String value : rowValues) {
                System.out.format("%-20s", value);
            }
            System.out.println();
        }
    } else {
        System.out.println("No data");
    }
}
/**
* displaySegments provides Segment details of the account
* @param segments
*/
public static void displaySegments(Segments segments) {

    for (Segment segment : segments.getItems()) {
        System.out.println("Advanced Segment ID: " + segment.getId());
        System.out.println("Advanced Segment Name: " + segment.getName());
        System.out.println("Advanced Segment Definition: "
                + segment.getDefinition());

    }

}

}

当我运行此代码时,它可以正常工作,它提供了一个授权链接,我得到了授权码,但是当在控制台中输入授权码时,它给出了这个错误:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/http/HttpParser
at GoogleAnalyticsExample.main(GoogleAnalyticsExample.java:64)
Caused by: java.lang.ClassNotFoundException: com.google.api.client.http.HttpParser
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
4

1 回答 1

0

在您的类路径中包含以下 jar google-http-client-1.5.0-beta.jar.... 另外,请确保在运行和编译代码时包含确切数量的 jar。

我在我的类路径中使用了以下 jar。可以排除大约 2-3 个罐子

jdk1.6.0_21/lib/tools.jar
google-api-client-1.15.0-rc.jar
mysql-connector-java-3.1.7-bin.jar
google-api-services-analytics-v3-rev50-1.15.0-rc.jar
google-api-services-analytics-v3-rev50-1.15.0-rc-javadoc.jar
google-api-services-analytics-v3-rev50-1.15.0-rc-sources.jar
google-http-client-1.15.0-rc.jar
google-http-client-jackson2-1.15.0-rc.jar
jackson-core-2.0.5.jar
google-oauth-client-1.15.0-rc.jar
于 2013-10-02T11:50:24.547 回答