Java Google Plus通过oAuth 2.0访问
为了读取个人资料数据,我尝试了很多不同的方法来访问谷歌账户,但每次都失败了Java Google Plus通过oAuth 2.0访问,java,oauth-2.0,google-plus,Java,Oauth 2.0,Google Plus,为了读取个人资料数据,我尝试了很多不同的方法来访问谷歌账户,但每次都失败了 Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized { "code" : 401, "errors" : [ { "domain" : "global", "location" : "Authorization",
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Invalid Credentials",
"reason" : "authError"
} ],
"message" : "Invalid Credentials"
}
我试图通过以下代码访问
@SuppressWarnings("deprecation")
public static GoogleAccessProtectedResource connect(String CLIENT_ID,String CLIENT_SECRET,String SCOPE,String CALLBACK_URL,HttpTransport TRANSPORT,JsonFactory JSON_FACTORY) throws IOException{
// Generate the URL to which we will direct users
String authorizeUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,
CALLBACK_URL, SCOPE).build();
System.out.println("Paste this url in your browser: " + authorizeUrl);
// Wait for the authorization code
System.out.println("Type the code you received here: ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String authorizationCode = in.readLine();
// Exchange for an access and refresh token
GoogleAuthorizationCodeGrant authRequest = new GoogleAuthorizationCodeGrant(TRANSPORT,
JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authorizationCode, CALLBACK_URL);
authRequest.useBasicAuthorization = false;
AccessTokenResponse authResponse = authRequest.execute();
String accessToken = authResponse.accessToken;
GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken,
TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authResponse.refreshToken);
HttpRequestFactory rf = TRANSPORT.createRequestFactory(access);
System.out.println("Access token: " + authResponse.accessToken);
// Make an authenticated request
GenericUrl shortenEndpoint = new GenericUrl("https://www.googleapis.com/urlshortener/v1/url");
String requestBody =
"{\"longUrl\":\"http://farm6.static.flickr.com/5281/5686001474_e06f1587ff_o.jpg\"}";
HttpRequest request = rf.buildPostRequest(shortenEndpoint,
ByteArrayContent.fromString("application/json", requestBody));
HttpResponse shortUrl = request.execute();
BufferedReader output = new BufferedReader(new InputStreamReader(shortUrl.getContent()));
System.out.println("Shorten Response: ");
for (String line = output.readLine(); line != null; line = output.readLine()) {
System.out.println(line);
}
// Refresh a token (SHOULD ONLY BE DONE WHEN ACCESS TOKEN EXPIRES)
//access.refreshToken();
//System.out.println("Original Token: " + accessToken + " New Token: " + access.getAccessToken());
return access;
}
然后我想访问我的帐户
public static void getData1(String accessToken, String clientId, String clientSecret, String refreshToken) throws IOException{
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
// Set up OAuth 2.0 access of protected resources
// using the refresh and access tokens, automatically
// refreshing the access token when it expires
GoogleAccessProtectedResource requestInitializer =
new GoogleAccessProtectedResource(accessToken, httpTransport,
jsonFactory, clientId, clientSecret, refreshToken);
// Set up the main Google+ class
Plus plus = Plus.builder(httpTransport, jsonFactory)
.setHttpRequestInitializer(requestInitializer)
.build();
// Make a request to access your profile and display it to console
Person profile = plus.people().get("[myID]").execute();
System.out.println("ID: " + profile.getId());
System.out.println("Name: " + profile.getDisplayName());
System.out.println("Image URL: " + profile.getImage().getUrl());
System.out.println("Profile URL: " + profile.getUrl());
}
以下主要方法应在之后工作:创建客户机ID
和客户机机密
public static void main(String[] args) throws IOException {
GoogleAccessProtectedResource access1=Connection.connect(CLIENT_ID, CLIENT_SECRET, SCOPE, CALLBACK_URL, TRANSPORT, JSON_FACTORY);
//refresh
String token= access1.getAccessToken();
access1.refreshToken();
String refreshed=access1.getAccessToken();
//get data
Connection.getData1(token, CLIENT_ID, CLIENT_SECRET, refreshed);
}
这是我的数据
private static final String SCOPE = "https://www.googleapis.com/auth/urlshortener";
private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
// FILL THESE IN WITH YOUR VALUES FROM THE API CONSOLE
private static final String CLIENT_ID = "[myID].apps.googleusercontent.com";
private static final String CLIENT_SECRET = "[myID]";
现在抛出了一个错误的请求异常
Exception in thread "main" com.google.api.client.http.HttpResponseException: 400 Bad Request
{
"error" : "invalid_client"
}
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:900)
at com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.executeUnparsed(AccessTokenRequest.java:472)
at com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.execute(AccessTokenRequest.java:486)
at Connection.connect(Connection.java:78)
at Connection.main(Connection.java:50)
希望这很容易修复 您使用的范围字符串为:
https://www.googleapis.com/auth/urlshortener
这是URL Shortener(goo.gl)API的范围,而不是Google+API。相反,您可能应该尝试使用谷歌的配置文件范围+
https://www.googleapis.com/auth/plus.me
此处的文档:
上面,您似乎正在使用[myID]引用两种不同类型的ID:
在下面的语句中,myID应该是您的Google+配置文件ID(从您的Google+配置文件的URL复制/粘贴,或者使用字符串“me”表示当前授权的用户):
Person profile=plus.people().get(“[myID]”)。execute()代码>
但是,对于客户端ID,您应该在code.google.com/api/console中使用项目中的值。谢谢Ryan,我尝试用您的建议修复它,但它不起作用。。。如你所说,我改变了范围。对于[myID],我使用了两种不同类型的ID。我只想把它们藏起来;)现在使用正确的作用域,您看到了什么异常?我在下面为这个主题添加了一个新的答案,因为它无法将代码发布到注释中!HttpResponseException被抛出。顺便说一句我正在写我的学士学位论文,我需要在Google+上获取并导出我个人资料的个人资料数据。这是正确的方法吗?你能做的最好的事情就是使用GooglePlus java初学者项目:请看这里:它现在可以工作了!我无法解释出哪里出了问题,我再次复制粘贴了客户ID和秘密,结果成功了。但如果您使用google plus java starter项目,它会更好、更简单: