Google reCaptcha:使用Java验证服务器端的用户响应

时间:2015-02-02 07:08:44

标签: java json recaptcha

我正在尝试按https://developers.google.com/recaptcha/docs/verifyGoogle 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在哪里。

我正在使用条带框架,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>

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

Ains,它足以从InputStream获取字符串然后实例化JSONObject:

        ...
        InputStream response = connection.getInputStream();
        // Take the string, Plain old JDK4 style
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
        String line = bufferedReader.readLine();
        while(line != null){
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        JSONObject json = new JSONObject(inputStringBuilder.toString());
        ...