Ros*_*ala 3 java validation servlets recaptcha invisible-recaptcha
这是一个Q&A风格的帖子,我将发布问题和答案.主要原因是我花了很多时间搜索验证recaptcha V2的最简单方法.因此,我将分享我的知识,以避免开发人员进一步浪费时间.
如何使用Java对Google reCAPTCHA V2或Invisible reCAPTCHA进行服务器端验证?
我正在使用org.json库.jar从这里获取文件或阅读文档.将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;
Run Code Online (Sandbox Code Playgroud)
使用以下方法进行验证.
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
调用上面的方法,如下所示,
if(isCaptchaValid("enter_your_key_here", request.getParameter("g-recaptcha-response"))){
//valid
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.干杯!
| 归档时间: |
|
| 查看次数: |
8956 次 |
| 最近记录: |