I am building a URL shortener and am working on the "follow method" - e.g. short.li/?stub=dishpods should redirect to https://www.amazon.com/gp/product/B07CTQ8THP/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
How do I set up this automatic redirect in my controller? The best I've been able to figure out is printing to the console, but I want it to automatically follow.
@GetMapping("/")
void follow(@RequestParam String stub) throws IOException, InterruptedException {
ShortUrl longUrl = repository.findByShortUrl(stub);
String longUrlString;
if (longUrl != null) {
longUrlString = longUrl.getShortUrl();
} else {
longUrlString = "https://google.com";
}
try {
URL myurl = new URL(longUrlString);
con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
StringBuilder content;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
System.out.println(content.toString());
} finally {
con.disconnect();
}
}