调用Google Captcha API进行服务器端验证时出现“无效密钥”错误

问题描述

代码如下

private Boolean validateCaptcha(String userCaptchaResponse) {
        Boolean isCaptchaValid = false;
        String response = null;

        try {
            URL verifyUrl = new URL("https://www.google.com/recaptcha/api/siteverify");

            // Open a Connection to URL above.
            HttpsURLConnection conn = (HttpsURLConnection) verifyUrl.openConnection();

            // Add the Header informations to the Request to prepare send to the server.
            conn.setRequestMethod("POST");

            // Data will be sent to the server.
            String postParams = "secret=" + SECRET_KEY
                    + "&response=" + userCaptchaResponse;

            // Send Request
            conn.setDoOutput(true);

            // Get the output stream of Connection.
            // Write data in this stream,which means to send data to Server.
            OutputStream outStream = conn.getoutputStream();
            outStream.write(postParams.getBytes());

            outStream.flush();
            outStream.close();

            // Response code return from Server.
            int responseCode = conn.getResponseCode();
            log.error("responseCode=" + responseCode);

            // Get the Input Stream of Connection to read data sent from the Server.
            try (BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
                StringBuffer sb = new StringBuffer();
                String output = "";
                while ((output = br.readLine()) != null) {
                    sb.append(output);
                }
                response = sb.toString();
            }

            log.error("Full Response = " + response);
            
            ObjectMapper mapper = new ObjectMapper();
            JsonNode resultNode = mapper.readTree(response);
            isCaptchaValid =  Boolean.valueOf(resultNode.path("success").asText());

        } catch (Exception e) {
            e.printstacktrace();
            return false;
        }

        return isCaptchaValid;
    }

有人可以帮助我了解此API调用在哪里出问题。 使用的站点密钥和秘密密钥有效。 我多次验证。

我可以通过邮递员获得成功的响应,但是当从应用程序中调用该响应时,它将引发此错误

{“成功”:否,“错误代码”:[“无效键”]}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)