我正在尝试为我的网站登录表单设置一个Google reCaptcha。但这对我不起作用。请帮忙。获取reCaptcha响应的NULL值。
我正在研究Spring-MVC Dynamic应用程序。
是否需要添加XML ????
JSP表单:
<form action="welcome" method="POST">
<div class="col" align="center">
<h1>Login</h1>
<hr>
<div class="g-recaptcha" data-sitekey="[Public key]"></div><br>
<button type="submit" class="btn btn-info btn-lg">Login</button>
</div>
</form>
控制器:
String username=request.getParameter("username");
String pwd=request.getParameter("pwd");
String response = request.getParameter("g-recaptcha");
System.out.println("reCaptcha Response: "+response);
String ipAddress = request.getRemoteAddr();
System.out.println("ReCaptcha: "+response);
boolean verify = VerifyRecaptcha.verify(response,ipAddress);
if(verify)
{
System.out.println("Captcha Successful");
}
else
{
System.out.println("Captcha Unsuccessful");
}
VerifyRecaptcha.java
public class VerifyRecaptcha {
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = "[secret key]";
public static boolean verify(String gRecaptchaResponse,String ipAddress) throws IOException
{
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse))
{
return false;
}
try
{
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User", ipAddress);
String postParams = "secret=" + secret + "&response="+ gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
//parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return jsonObject.getBoolean("success");
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
}
控制台上的输出(打印的语句)
reCaptcha响应:null
ReCaptcha:空
验证码失败