如何使用gmail api获取访问令牌

tqj*_*stc 12 java google-api gmail-api

我在本文档后面获得了授权码.但是当我试图获得访问令牌时,我总是遇到错误.谁能帮我 ?

public String AccessToken()
{
    String accessToken = "";
    StringBuilder strBuild = new StringBuilder();

    String authURL = "https://accounts.google.com/o/oauth2/token?";
    String code = "4/SVisuz_x*********************";
    String client_id = "******************e.apps.googleusercontent.com";
    String client_secret = "*******************";
    String redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
    String grant_type="authorization_code";
    strBuild.append("code=").append(code)
            .append("&client_id=").append(client_id)
            .append("&client_secret=").append(client_secret)
            .append("&redirect_uri=").append(redirect_uri)
            .append("&grant_type=").append(grant_type);
    System.out.println(strBuild.toString());
    try{
        URL obj = new URL(authURL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Host", "www.googleapis.com");

        //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
        //bw.write(strBuild.toString());
        //bw.close();

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(strBuild.toString());
        wr.flush();
        wr.close();

        //OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
        System.out.println(con.getResponseCode());
        System.out.println(con.getResponseMessage());             

    } catch (Exception e)
    {
        System.out.println("Error.");
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,输​​出是: 400 Bad Request

Sky*_*ker 11

如何使用gmail api获取访问令牌?

答:根据您的以下教程,您正在使用OAuth 2.0.因此,有一种使用Google API访问的基本模式OAuth 2.0.它遵循4个步骤:

  1. 从Google Developers Console获取OAuth 2.0凭据.
  2. 从Google Authorization Server获取访问令牌.
  3. 将访问令牌发送到API.
  4. 如有必要,刷新访问令牌.

有关详细信息,您可以按照教程 - 使用OAuth 2.0访问Google API

您必须访问Google Developers Console才能获取OA client IDclient secretGoogle 凭据,例如Google和您的应用程序都知道的凭据


根本原因分析:

问题1:

在研究了你的代码后,发现了一些缺乏的代码.如果代码运行顺畅,那么代码总是给出一个空字符串.因为你的AccessToken()方法总是返回return "";

问题2:

 catch (Exception e)
    {
        System.out.println("Error.");
    }
Run Code Online (Sandbox Code Playgroud)

你的try catch块正在进行异常块.因为,您似乎还没有正确完成代码.您已经错过了encoding使用JSONObject哪个准备访问令牌.所以它给出了输出

错误.

解:

我知道你的代码与本教程类似

因为您的代码需要更多更改来解决您的问题.所以我建议你使用LinkedHashMapArrayList.这些将提供更简单的解决方案.所以我给你2个示例代码,让你的生活更轻松.你可以选择其中任何一个.你需要改变refresh_token, client id, client secret and grant type你的.

private String getAccessToken()
{
    try
    {
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("grant_type","refresh_token");
        params.put("client_id",[YOUR CLIENT ID]);
        params.put("client_secret",[YOUR CLIENT SECRET]);
        params.put("refresh_token",[YOUR REFRESH TOKEN]);

        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://accounts.google.com/o/oauth2/token");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.getOutputStream().write(postDataBytes);

        BufferedReader  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 ex)
    {
        ex.printStackTrace(); 
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

访问google play android developer api,您需要传递先前的刷新令牌以获取访问令牌

private String getAccessToken(String refreshToken){

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
try 
{
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("grant_type",    "refresh_token"));
    nameValuePairs.add(new BasicNameValuePair("client_id",     GOOGLE_CLIENT_ID));
    nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    org.apache.http.HttpResponse response = client.execute(post);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    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 (IOException e) { e.printStackTrace(); }

return null;
}
Run Code Online (Sandbox Code Playgroud)

资源链接:

希望,这samplesresource link将帮助你解决你的问题,得到的访问access token.


什么是400坏请求?

Ans:表示查询无效.缺少父ID或请求的维度或指标组合无效.

推荐的操作:您需要对API查询进行更改才能使其正常工作.

因为HTTP/1.1 400 Bad Request error,你可以通过我的另一个答案.它将帮助您了解which host you need to use您需要应用的条件.

为什么令牌到期?令牌的限制是什么?

由于以下原因之一,令牌可能会停止工作:

  1. 用户有权revoked访问.
  2. 该令牌尚未用于six months.
  3. user changed passwords标记包含Gmail,日历,通讯录或环聊范围.
  4. 用户帐户有exceeded a certain number of token requests.

currently a limit of 25 refresh tokens per user account per client.如果达到限制,则创建新令牌会自动使最旧的令牌无效而不会发出警告.此限制不适用于服务帐户.

应遵循哪些预防措施?

注意事项 - 1:

某些请求需要身份验证步骤,用户使用其Google帐户登录.登录后,系统会询问用户是否愿意授予应用程序请求的权限.此过程称为用户同意.

如果用户授予权限,Google Authorization Server会向您的应用程序发送访问令牌(或您的应用程序可用于获取访问令牌的授权码).如果用户未授予权限,则服务器返回错误.

注意事项 - 2:

如果为Google+ API发放了访问令牌,则不会授予对Google通讯录API的访问权限.但是,您可以多次将该访问令牌发送到Google+ API以执行类似操作.

注意事项 - 3:

访问令牌通常具有1小时的到期日期,之后如果您尝试使用它,则会出现错误.Google Credential 会自动"刷新"令牌,这意味着获取新的访问令牌.

在安全的长期存储中保存刷新令牌,并且只要它们仍然有效,就继续使用它们.限制适用于每个客户端 - 用户组合以及所有客户端中的每个用户发布的刷新令牌的数量,并且这些限制是不同的.如果您的应用程序请求足够的刷新令牌超过其中一个限制,则较旧的刷新令牌将停止工作.


new*_*use 3

您没有使用正确的端点。尝试更改authURLhttps://www.googleapis.com/oauth2/v4/token

从文档中:

要发出此令牌请求,请将 HTTP POST 请求发送到 /oauth2/v4/token 端点

实际的请求可能如下所示:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret=your_client_secret&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
Run Code Online (Sandbox Code Playgroud)

参考 https://developers.google.com/identity/protocols/OAuth2InstalledApp#handlingtheresponse