我想将google recaptcha用于我的网站。我的网络有一个代理。因此我无法在网络中很好地检查Recaptcha。然后我得到SSLHandshake异常。因此,我在Java类中使用了以下代码。然后我得到java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Invalid URI
这个异常。
我想知道的另一件事是使用代理可以获取SSLHansshake异常的解决方案。我试图为我的本地主机获得免费的SSL认证。但这也没有成功。有没有使用SSL认证的另一种使用Recaptcha服务的方法。
我用下面的代码..帮我解决了这个问题
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.net.URL;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.net.ssl.HttpsURLConnection;
import org.apache.log4j.Logger;
import java.net.Proxy;
public class VerifyRecaptcha {
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = "secret_key";
private final static String USER_AGENT = "Mozilla/5.0";
//messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("risk.for.ip.block"));
static Logger logger = Logger.getLogger(VerifyRecaptcha.class);
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080));
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(proxy);
// 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();
logger.debug("\nSending 'POST' request to URL : " + url);
logger.debug("Post parameters : " + postParams);
logger.debug("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();
//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){
logger.fatal("Error :>",e);
return false;
}
}
}