我正在尝试使用刷新 token (从 OAuth Playground 颁发)访问 GoogleDrive API(我自己的 a/c),如下所示。我正在使用刷新 token 和访问 token 进行离线访问,但收到未经授权的 401 错误。我的代码基于引用 belwo 和 google-api javadocs 建议来构建离线请求
我不想使用浏览器,我希望从服务器端应用程序运行它以上传到我自己的帐户。
ref: http://stackoverflow.com/questions/10533203/fetching-access-token-from-refresh-token-using-java
代码:
public static void main(String[] args) throws IOException {
HttpTransport TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
String refreshTokenString="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //from console
String accessTokenString ="yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; //from console
GoogleCredential credential = createCredentialWithRefreshToken(
TRANSPORT, JSON_FACTORY, new TokenResponse().setRefreshToken(refreshTokenString));
credential.setAccessToken("accessTokenString");
//exeucute HTTP request for offline accessTokenString
// Execute HTTP GET request to revoke current token.
HttpResponse response = TRANSPORT.createRequestFactory()
.buildGetRequest(new GenericUrl(
String.format(
"https://www.googleapis.com/drive/v2/changes",
credential.getAccessToken()))).execute();
System.out.println("RESPONSE: " +response);
}
public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
JsonFactory jsonFactory, TokenResponse tokenResponse) {
HttpTransport TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build()
.setFromTokenResponse(tokenResponse);
}
错误:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
我正在使用有效的刷新 token 和访问 token (在 Playground 控制台工作),但从 Java 应用程序运行时,我在此处收到需要登录 401 的消息。我需要使用此功能将日常备份从服务器直接备份到云端硬盘。
最佳答案
您无法在应用程序中使用来自 Playgorund 的访问或刷新 token 。这些 token 由谷歌发行,仅供 Playground 使用。您获得的 token 与客户端 ID 和客户端 key 相关联。显然,您的 CLIENT_ID 和 CLIENT_SECRET 与 Google Playground 应用程序使用的不同。
您确实需要您的应用程序来请求这些 token ,因此您第一次需要一个浏览器,以便用户可以接受您的应用程序(而不是 Google Playground)正在获取存储在 Google 中的您的信息。这称为“用户同意”,如本页的小图表所示:Using OAuth 2.0 for Web Server Applications )
然后,当您拥有应用程序的刷新 token 时。您不再需要浏览器来进行日常备份。 您可以将代码与应用程序的有效刷新 token 一起使用,如您的帖子中所示。
关于oauth-2.0 - 使用刷新 token 访问 Google Drive API,无浏览器,401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28595677/