Is it possible to get the reloaded url in Java?
I need to retrieve the token append to the url after loading below HTML page.
Initially the URL will be
http://localhost:8080/validate.html?invisible=true
After the successful google-recaptcha it will be
http://localhost:8080/validate.html?token=xyz
I need to retrieve the token value in Java.
I have tried with the below piece of code but the location var is returning null.
Any solutions?
final String htmlUrl = "http://localhost:8080/validate.html?invisible=true";
HttpURLConnection con = (HttpURLConnection)(new URL( htmlUrl ).openConnection());
con.setInstanceFollowRedirects( true );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );
<html>
<script> function reCaptchaCallback(token){ window.location = '?token=' + token; } </script>
<script src="https://www.google.com/recaptcha/**.js?render=123"></script>
<script src="https://www.google.com/recaptcha/**.js?onload=onloadCallback&render=explicit"></script>
<script>
const url = new URL(window.location.href);
if (!url.searchParams.get('token')) {
if (url.searchParams.get('visible') != 'true') {
grecaptcha.enterprise.ready(function() {
grecaptcha.enterprise.execute('123', {action: 'homepage'}).then(function(token) {
reCaptchaCallback(token);
});
});
}
}
</script>
<script type="text/javascript">
var onloadCallback = function() {
if (url.searchParams.get('visible') == 'true') {
grecaptcha.enterprise.render('recaptcha', { 'sitekey' : '123', 'callback': 'reCaptchaCallback' });
}
};
</script>
<body style= "display: flex; align-items: center; justify-content: center;">
<div id="recaptcha"></div>
</body>
</html>
What you are trying to do is not possible (at least with HttpURLConnection)
First problem is that Location header is set by a web server to redirect user.
You are altering the location clientside by changing window.location (which is not related to Location header sent when loading the site.
Second problem is that HttpURLConnection only does one request that loads validate.html. Creating a connection doesn't work like opening a website with your browser. Your browser does much more (it parses the HTML, loads images, scripts and other files, executes javascript / wasm files and renders your html/css after connecting and getting contents of your validate.html).
You could do something like this by using a headless browser such as chromium. For that you will need to use a library like Selenium