谷歌验证码 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);
    }
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注