【发布时间】:2019-04-04 15:31:35
【问题描述】:
我正在尝试向 Google 联系人 API 验证我的应用程序。我已经完成了 Oauth2 流程的第一步,并获得了授权码。我正在尝试将此代码交换为访问令牌和刷新令牌,但是当我尝试从 googleapis.com/oauth2/v4/token 获取令牌时,使用
响应:“invalid_grant”“错误请求”错误 400。
我的代码
try
{
Map<String,Object> params = new LinkedHashMap<>();
params.put("grant_type","authorization_code");
params.put("code", authCode);
params.put("client_id",CLIENTE_ID);
params.put("client_secret",CLIENTE_ID_SECRETO);
params.put("redirect_uri","http://localhost:8080/conob/api2/contatos/insert");
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet())
{
if(postData.length() != 0){
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = new URL("https://www.googleapis.com/oauth2/v4/token");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Length", postData.toString().length() + "");
con.getOutputStream().write(postDataBytes);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()){
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
String accessToken = json.getString("access_token");
return accessToken;
} catch (Exception e) {
reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()){
buffer.append(line);
}
System.out.println(buffer.toString());
System.out.println(e.toString());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
参数输出:
grant_type=authorization_code&code=AUTHORIZATION_CODE&client_id=CLIENTE_ID&client_secret=CLIENTE_SECRET&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fconob%2Fapi2%2Fcontatos%2Finsert
我在许多论坛中搜索了很多小时,但没有找到解决我问题的方法。
基本上,我的应用需要在公司 Intranet 的 google 帐户上插入新联系人。
我的问题是“invalid_grant”的响应是什么?
好的代码,从现在开始感谢;
【问题讨论】:
-
在这种情况下,响应是“Bad Request”,对不起:/
-
任何你不使用google api java client library的原因
-
@bogl 这个问题对我来说很清楚。但是,由于您在理解它时遇到问题,我已经编辑了他的问题。现在清楚了吗?
-
欢迎使用 stackoverflow,尼古拉斯!这个问题现在更具可读性,非常感谢!
标签: java google-api google-oauth google-contacts-api