这是一篇问答式的帖子,我会同时发布问题和答案。这样做的主要原因是我花了很多时间寻找最简单的方法来验证 recaptcha V2。因此,我将分享我的知识,以避免开发人员进一步浪费时间。
How to do a server side validation of Google reCAPTCHA V2 or Invisible reCAPTCHA with Java?
最佳答案
为此,我正在使用 org.json
库。从 here 获取 jar
文件或阅读 docs .将 jar 文件添加到您的项目并导入以下类。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
使用以下方法进行验证。
/**
* Validates Google reCAPTCHA V2 or Invisible reCAPTCHA.
*
* @param secretKey Secret key (key given for communication between your
* site and Google)
* @param response reCAPTCHA response from client side.
* (g-recaptcha-response)
* @return true if validation successful, false otherwise.
*/
public synchronized boolean isCaptchaValid(String secretKey, String response) {
try {
String url = "https://www.google.com/recaptcha/api/siteverify",
params = "secret=" + secretKey + "&response=" + response;
HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream res = http.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(res, "UTF-8"));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
JSONObject json = new JSONObject(sb.toString());
res.close();
return json.getBoolean("success");
} catch (Exception e) {
//e.printStackTrace();
}
return false;
}
如下所示调用上面的方法,
if(isCaptchaValid("enter_your_key_here", request.getParameter("g-recaptcha-response"))){
//valid
}
希望这对您有所帮助。干杯!
编辑:
按照 Google 的建议使用 POST
方法验证信息, 更安全,但是如果您需要 GET
方法版本,请引用 edit history .
不要对 params
变量进行编码。这样做您将始终得到以下响应。
{"error-codes":["missing-input-response","missing-input-secret"],"success":false}
关于java - 如何验证 reCAPTCHA V2 Java (Servlet),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47622506/