我嘗試使用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相關?
此致敬禮, 謝爾蓋。
我看到了創建憑證對象的代碼 - 您是否也可以共享代碼使用該對象來創建API請求? – aeijdenberg
嗨@aeijdenberg!感謝您的回答。我已將Analytics對象和查詢代碼添加到主帖子中。謝謝。 –