The main reason for this post 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.
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.net.URL;
import java.nio.charset.Charset;
import org.json.JSONObject;
Use the following method to 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 static boolean isCaptchaValid(String secretKey, String response) {
try {
String url = "https://www.google.com/recaptcha/api/siteverify?"
+ "secret=" + secretKey
+ "&response=" + response;
InputStream res = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(res, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
String jsonText = sb.toString();
res.close();
JSONObject json = new JSONObject(jsonText);
return json.getBoolean("success");
} catch (Exception e) {
return false;
}
}
Call the above method as shown:
if(isCaptchaValid("enter_your_key_here", request.getParameter("g-recaptcha-response"))){
//valid
}