簡體   English   中英

Gmail api 出現錯誤 400“invalid_grant”

[英]Gmail api thows an error 400 "invalid_grant"

我使用 google oauth playground 生成了刷新令牌。 我使用此刷新令牌在下面的 java 代碼中生成新的訪問令牌。 4 天前它工作正常。但現在我看到以下錯誤,POST https://oauth2.googleapis.com/token { "error": "invalid_grant", "error_description": "Token has been expired or revoked. " 如果我從 oauth2 游樂場生成新的刷新令牌並替換我的 credentials.json 上的現有令牌,它工作正常。但如果我幾天沒有執行代碼,同樣的錯誤。我不確定我是什么失蹤。 我的java代碼

 private String getAccessToken() {
        try {
            credentials.put("grant_type", "refresh_token");
            credentials.put("client_id", credential.get("client_id"));
            credentials.put("client_secret", credential.get("client_secret"));
            credentials.put("refresh_token", credential.get("refresh_token"));
            credentials.put("project_id", credential.get("project_id"));
        
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, Object> param : credentials.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) {
            log.error("Error on generating access token:"+ExceptionUtils.getFullStackTrace(ex));
        }
        return null;
    }

如果 Java 應用程序長時間未連接到 Gmail 服務器,則 API 服務將被禁止。 您可以通過訪問 Google 帳戶設置並重新打開它來重新設置它。
您需要打開“開啟”以允許不太安全的應用程序連接; 可以在這里找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM