0

我尝试使用 java 库和服务帐户从 GA 获取数据。我已经完成了所有必需的设置:在云控制台中激活 Analytics API,生成服务帐户,获取私钥,在 GA 用户管理中添加生成的具有读取权限的开发人员电子邮件。

使用我的本地实现,这可以正常工作。但是当我尝试从服务器端运行相同的代码时,我收到状态“需要 401 未经授权的登录”。两种实现都使用 Java 5 运行时,Google API 服务 Java 库版本 1.17.0 rev75。

带有凭据定义的代码片段:

    HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    JsonFactory JSON_FACTORY = new JacksonFactory();    

    GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(HTTP_TRANSPORT)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId("xxx@developer.gserviceaccount.com")
    .setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
    .setServiceAccountPrivateKeyFromP12File(new File("privatekey.p12"))
    .build();

Analytics 对象和查询构建器:

Analytics analytics = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("MyApp")
.build();

Get apiQuery = analytics.data().ga().get("ga:123", "2013-12-09","2013-12-09", "ga:visits");
HttpResponse response = apiQuery.executeUnparsed();

我已经添加了 httpLogger 来比较流量。我看到在本地和服务器运行的情况下,授权流程是相同的,获取访问令牌没有问题。

通过本地运行,我收到状态为 200 的响应:

    CONFIG: -------------- RESPONSE --------------
    HTTP/1.1 200 OK
    Alternate-Protocol: 443:quic
    ETag: "xxxx"
    Date: Mon, 30 Dec 2013 13:12:32 GMT
    Content-Type: application/json; charset=UTF-8
    X-Content-Type-Options: nosniff
    Cache-Control: private, max-age=0, must-revalidate, no-transform
    Content-Length: 1728
    Content-Encoding: gzip
    X-XSS-Protection: 1; mode=block
    Expires: Mon, 30 Dec 2013 13:12:32 GMT
    X-Frame-Options: SAMEORIGIN
    Server: GSE
{JSON BODY}

但是随着服务器运行,我收到了状态为 401 的响应:

CONFIG: -------------- RESPONSE --------------
401 Unauthorized
date: Mon, 30 Dec 2013 13:17:32 GMT
alternate-protocol: 443:quic
server: GSE
www-authenticate: Bearer realm="https://www.google.com/accounts/AuthSubRequest"
transfer-encoding: chunked
expires: Mon, 30 Dec 2013 13:17:32 GMT
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
content-type: application/json; charset=UTF-8
cache-control: private, max-age=0
    {"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}

有人可以帮助我吗?我真的检查了我所知道的一切,但没有运气。

编辑 是否有人知道将域范围内的授权委托给服务帐户是否与 Google Analytics API 相关?

最好的问候,谢尔盖。

4

1 回答 1

0

该问题已通过将传输更改为 ApacheHttpTransport 类得到解决。

但是了解 NetHttpTransport 出了什么问题会非常有用。

问候,谢尔盖。

于 2014-01-11T16:50:36.870 回答