谷歌+;api-密钥来自https://accounts.google.com/o/oauth2/token 给出401个错误
我在使用Google+API OAuth2令牌时遇到了一些问题 下面是一个获取OAuth2访问令牌的简单程序:谷歌+;api-密钥来自https://accounts.google.com/o/oauth2/token 给出401个错误,api,oauth-2.0,google-plus,Api,Oauth 2.0,Google Plus,我在使用Google+API OAuth2令牌时遇到了一些问题 下面是一个获取OAuth2访问令牌的简单程序: HttpClient httpclient = new HttpClient(); PostMethod postMethod = new PostMethod("https://accounts.google.com/o/oauth2/token"); NameValuePair[] data = { new NameV
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.AHES6ZTZGPTKYZ530MOYVDPAEXVJK5DWQZPQXONEL2C7GSQWGFMTT8Q
然后我设置了一个简单的测试程序,可以测试从该令牌调用/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);
}
@测试
public void TestGoogleAppAuthdRequest()引发异常{
字符串feedUrl=”https://www.googleapis.com/plus/v1/people/me";
String apiKey=“我的API密钥”;
字符串oauthCode=“上面的OAUTH代码”;
字符串jsonStr=executegoglefeed(feedUrl、apiKey、oauthCode);
}
公共响应ExecuteLogleFeed(字符串feedURL、字符串apiKey、字符串oauthCode)引发异常{
StringBuilder urlStr=新的StringBuilder();
urlStr.append(feedURL);
urlStr.append(“?key=”);
urlStr.append(apiKey);
Map hashMap=新hashMap();
hashMap.put(“授权”、“承载人”+oauthCode);
返回HttpUtil.doHttpRequest(urlStr.toString(),MethodType.GET.toString(),null,
hashMap);
}
这给了我一个401错误。拒绝许可
当我转到时,令牌显示为有效
另外,当我转到并从OAuth2登录功能获取OAuth令牌时。。。我将OAuth令牌插入我的JUnit测试中。。。它起作用了
有人知道为什么我对的调用不能在Google+的api中用作承载参数吗 听起来根本的问题是,当您发送用户对自己进行身份验证并授权您的应用程序时,您没有请求plus.me作用域。这是在前面的步骤中完成的,它是返回前面添加的OAuth2“代码”的组件。您可能希望更新您的示例,以说明如何获取代码以及使用什么作用域来实现这一点 如果正确设置了作用域,并且使用了返回的代码,则可能是继续使用相同的代码。从第一阶段返回的OAuth2代码只能使用一次,并且在发布后必须非常快地使用。它被交换为具有有限生存期的访问令牌(这是您正确尝试的操作),以及具有无限生存期的刷新令牌,用于生成新的访问令牌
有关获取并交换OAuth2代码的多步骤过程的详细信息,请参阅。我正要来回答我自己的问题。实际上,我使用了错误的范围,因为谷歌以一种隐秘的方式记录了它。好东西,谢谢。请注意,如果使用plus.login作用域,则不需要plus.me作用域。