我在使用 Google+ API OAuth2 令牌时遇到了一些问题。
这是一个获取 OAuth2 访问令牌的简单程序:
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new PostMethod("https://accounts.google.com/o/oauth2/token");
NameValuePair[] data = {
new NameValuePair("client_id", "API KEY HERE"),
new NameValuePair("redirect_uri", "URL HERE"),
new NameValuePair("client_secret", "SECRET HERE"),
new NameValuePair("code", "CODE HERE"),
new NameValuePair("grant_type", "authorization_code")
};
postMethod.setRequestBody(data);
try {
int result = httpclient.executeMethod(postMethod);
assertEquals(result, 200);
System.out.println("Response body: ");
System.out.println(postMethod.getResponseBodyAsString());
} catch (IOException e) {
e.printStackTrace();
}
这成功生成了 OAuth2 令牌。如:ya29.AHES6ZTZgptKHyZ530MoYVDPaeXvjK5DWQzPqxoNNEL2C7gsQwGfmvfT8Q
然后我设置了一个简单的测试程序,可以测试从该令牌调用 /people API:
@Test
public void testGoogleAPIAuthdRequest() throws Exception {
String feedUrl = "https://www.googleapis.com/plus/v1/people/me";
String apiKey = "MY API KEY";
String oauthCode = "OAUTH CODE FROM ABOVE";
String jsonStr = executeGoogleFeed(feedUrl, apiKey, oauthCode).getResponseBodyAsString("UTF-8");
}
public Response executeGoogleFeed(String feedURL, String apiKey, String oauthCode) throws Exception {
StringBuilder urlStr = new StringBuilder();
urlStr.append(feedURL);
urlStr.append("?key=");
urlStr.append(apiKey);
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Authorization", "Bearer " + oauthCode);
return HttpUtil.doHttpRequest(urlStr.toString(), MethodType.GET.toString(), null,
hashMap);
}
这给了我一个 401 错误。没有权限。
当我转到https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=INSERT_ACCESS_TOKEN时,令牌显示为有效。
此外,当我转到https://developers.google.com/+/api/latest/people/get并从 OAuth2 登录功能获取 OAuth 令牌时......我将该 OAuth 令牌插入到我的 JUnit 测试中... 有用!
有人知道为什么我对https://accounts.google.com/o/oauth2/token的调用不能用作 Google+ api 中的 Bearer 参数吗?