【发布时间】:2015-04-01 02:21:07
【问题描述】:
我正在尝试实现如 https://developers.google.com/recaptcha/docs/verify 和 Google reCAPTCHA: how to get user response and validate in the server side 中所示的 Google reCAPTCHA,但我无法在响应中获得成功字段。
不知道问题出在请求还是解析响应,这是我的代码:
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来自https://github.com/douglascrockford/JSON-java,json总是为空,但是在响应InputStream中找不到成功字段,所以不知道bug在哪里。
我用的是stripes框架,JSP代码是:
<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>
任何建议将不胜感激。
【问题讨论】: