我在Struts 2框架上有一个现有的Java应用程序。在尝试从captcha v1迁移并实现v2时,我没有任何运气。我希望有人可以提供帮助,我认为这应该是基本的。在我点击提交之前,我不是一个机器人只是在点击时旋转并且没有任何东西进入我的动作类。我已经尝试用我的实际密钥硬编码替换jsp中的sitekey。没运气。以下是我的新代码片段:
my.jsp
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey=<s:property value="#session.captchaPublicKey"/>"></div>
在我提交的行动小组中:
public void validateCaptcha() throws Exception{
logger.debug("in captcha validate");
String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
System.out.println(gRecaptchaResponse);
boolean verify = Captcha.verify(gRecaptchaResponse);
System.out.println("Captcha Verify"+verify);
//RequestDispatcher rd = getServletContext().getRequestDispatcher(
if (!verify == true) {
addActionError("You missed the Captcha.");
}
}
我的Captcha.java类
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.net.ssl.HttpsURLConnection;
public class Captcha {
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = WamProps.getProperty("RECAPTCHA_PRIVATEKEY");
private final static String USER_AGENT = "Mozilla/5.0";
public static boolean verify(String gRecaptchaResponse) 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-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
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;
}
}
}