谷歌验证码 ReCAPTCHA HTML前端配置

在前端HTML中导入ReCAPTCHA的api

<script src="https://recaptcha.net/recaptcha/api.js?onload=reCaptchaOnLoadCallback" async defer></script>

然后在需要验证码的位置添加验证码框 (把{SITE_KEY}替换成你自己的KEY)

<div id="g-recaptcha-box" style="margin: auto" class="g-recaptcha" data-callback="" data-sitekey="{SITE_KEY}"></div>

在JavaScript获取验证后的响应信息

//获取recaptcha的response
let response = grecaptcha.getResponse()
if (response === "") {
    //如果response为空,则抖动人机验证框进行提示
    //TODO 抖动效果
}

将response随表单提交到后端进行校验

谷歌验证码 ReCAPTCHA JAVA

package cn.nzdev.web.user_center.utils;

import com.google.gson.Gson;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author 玖洲丿林
 * @version 1.0
 * @implNote TODO
 * @implSpec TODO
 * @ClassName ReCaptchaUtil
 * @CreateDate 2021/2/25 20:51
 */
public class ReCaptchaUtil {

    private static final String CAPTCHA_KEY = "g-recaptcha-response";

    public static boolean validation(HttpServletRequest request) {
        String response = getGreCaptchaResponse(request);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://recaptcha.net/recaptcha/api/siteverify");
        ArrayList<NameValuePair> param = new ArrayList<>();
        param.add(new BasicNameValuePair("secret", "TEST"));
        param.add(new BasicNameValuePair("response", response));
        httpPost.setEntity(new UrlEncodedFormEntity(param, StandardCharsets.UTF_8));
        CloseableHttpResponse execute;
        try {
            execute = httpClient.execute(httpPost);
        } catch (IOException e) {
            return false;
        }
        if (execute.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            return false;
        }
        String responseEntity;
        try {
            responseEntity = EntityUtils.toString(execute.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            return false;
        }
        System.out.println(responseEntity);
        Gson gson = new Gson();
        Map<?,?> map = gson.fromJson(responseEntity, Map.class);
        Object success = map.get("success");
        try {
            return Boolean.parseBoolean(success.toString());
        } catch (Exception e) {
            return false;
        }
    }

    private static String getGreCaptchaResponse(HttpServletRequest request) {
        return request.getParameter(CAPTCHA_KEY);
    }
}