我在用着org.json
为此的图书馆。获取jar
文件来自here http://central.maven.org/maven2/org/json/json/20140107/json-20140107.jar或阅读docs https://mvnrepository.com/artifact/org.json/json/20140107。将 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
}
希望这可以帮助。干杯!
EDIT:使用POST
方法来验证信息的建议Google https://developers.google.com/recaptcha/docs/verify#api_request,更安全,但是如果您需要GET
方法版本请参考编辑历史记录 https://stackoverflow.com/revisions/47622507/3.
不要编码params
多变的。这样做您将始终得到以下响应。
{"error-codes":["missing-input-response","missing-input-secret"],"success":false}