如何验证reCAPTCHA V2 Java(Servlet) [英] How to validate reCAPTCHA V2 Java (Servlet)
问题描述
这是Q& A风格的帖子,我将同时发布问题和答案.造成这种情况的主要原因是,我花了很多时间搜索最简单的验证Recaptcha V2的方法.因此,我将分享我的知识,以避免开发人员进一步浪费时间.
This is an Q&A style post, which I'll post both the question and an answer. The main reason for this is that I spent quite a lot of time searching the easiest way to validate recaptcha V2. So I'm going to share my knowledge to avoid further time wastage of developers.
如何使用 Java 对Google reCAPTCHA V2 或不可见的reCAPTCHA 进行服务器端验证?>
How to do a server side validation of Google reCAPTCHA V2 or Invisible reCAPTCHA with Java?
推荐答案
我正在为此使用org.json
库.从此处获取jar
文件或阅读文档.将jar文件添加到您的项目中,并导入以下类.
I'm using org.json
library for this. Get the jar
file from here or read the docs. Add the jar file to your project and import the following classes.
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;
使用以下方法进行验证.
Use the following method for validation.
/**
* 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;
}
按如下所示调用上述方法,
Call the above method as shown below,
if(isCaptchaValid("enter_your_key_here", request.getParameter("g-recaptcha-response"))){
//valid
}
希望这会有所帮助.干杯!
Hope this helps. Cheers!
使用POST
方法验证 Google 推荐的信息更安全,但是,如果需要GET
方法版本,请参考编辑历史记录.
Using the POST
method to verify information as recommended by Google, is way more safer, however if you need the GET
method version please refer the edit history.
不对params
变量进行编码.这样一来,您将始终得到以下答复.
Don't encode the params
variable. You will always get the below response by doing so.
{"error-codes":["missing-input-response","missing-input-secret"],"success":false}
这篇关于如何验证reCAPTCHA V2 Java(Servlet)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!