Google AnalyticsJava API“401 Unauthorized Login Required”错误

时间:2014-01-10 11:49:13

标签: java oauth-2.0 google-analytics-api google-oauth google-oauth-java-client

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

使用我的本地实现,这很好。但是当我尝试从服务器端运行相同的代码时,我收到状态“401 Unauthorized Login Required”。这两种实现都使用Java 5运行时,Google API服务Java libs版本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 AnalyticsAPI相关?

祝你好运, 塞吉。

1 个答案:

答案 0 :(得分:0)

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

但要了解NetHttpTransport的错误是非常有用的。

此致,谢尔盖。