0

我尝试使用java库和服务帐户从GA获取数据。我做了所有必需的设置:在云控制台中激活Analytics API,生成服务帐户,获取私钥,添加生成的开发人员电子邮件,并在GA用户管理中拥有读取权限。谷歌分析Java API“401未经授权的登录”错误

用我的本地实现,这工作正常。但是当我尝试从服务器端运行相同的代码时,我收到状态“401 Unauthorized Login Required”。这两个实现都使用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("[email protected]") 
    .setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY)) 
    .setServiceAccountPrivateKeyFromP12File(new File("privatekey.p12")) 
    .build(); 

的分析对象和查询生成器:

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(); 

I`ve添加httpLogger来比较流量。我发现在本地和服务器运行的情况下,授权流程相同,访问令牌没有问题。

随着本地运行I`ve收到的响应与状态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} 

但是,随着服务器运行I`ve与状态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相关?

此致敬礼, 谢尔盖。

+0

我看到了创建凭证对象的代码 - 您是否也可以共享代码使用该对象来创建API请求? – aeijdenberg

+0

嗨@aeijdenberg!感谢您的回答。我已将Analytics对象和查询代码添加到主帖子中。谢谢。 –

回答

0

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

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

谢谢,谢尔盖。

相关问题