I am trying to implement Google reCAPTCHA as shown in https://developers.google.com/recaptcha/docs/verify and Google reCAPTCHA: how to get user response and validate in the server side, but I can't get the success field in the response.
I don't know if the problem is in the request or parsing the response, here is my code:
public Resolution contact(){
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
try {
String reCaptcha = context.getRequest().getParameter("g-recaptcha-response");
String urlReCaptcha = String.format("https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s"
, URLEncoder.encode(mySecretKey,charset)
, URLEncoder.encode(reCaptcha,charset)
, URLEncoder.encode(context.getRequest().getHeader("X-FORWARDED-FOR")!=null?context.getRequest().getHeader("X-FORWARDED-FOR"):context.getRequest().getRemoteAddr(),charset));
URLConnection connection;
connection = new URL(urlReCaptcha).openConnection();
InputStream response = connection.getInputStream();
JSONObject json = new JSONObject(response);
String success = json.get("success").toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ForwardResolution(VIEW_SUCCESS);
}
JSONObject is from https://github.com/douglascrockford/JSON-java, json is always empty, but I can't find success field in response InputStream, so I don't know where is the bug.
I'am using stripes framework, the JSP code is:
<stripes:form beanclass="es.package.ContactActionBean">
<fieldset class="form-group">
<!-- Some fields -->
<input type="submit" name="contact" value="SEND" class="btn btn-success btn-sm"/>
</fieldset>
<div class="g-recaptcha" data-sitekey="my_public_key"></div>
</stripes:form>
Any suggestions will be appreciated.