0

If you search some sites like https://www.uncox.com/ in the browsers,the browser will load the address https://learn.uncox.com/. And when I print the response code, server returns 200!!!. Not 300 and ...and headers locations value is null.

Now my question is, how can I use Java get the latest URL (the URL that will be loaded by browser at the end) from a URL?

halfer
  • 19,824
  • 17
  • 99
  • 186
Hadi
  • 544
  • 1
  • 8
  • 28

1 Answers1

2

The way this is implemented in the browsers (and I'm simplifying it a lot) is that the server would send HTTP code 301 (permanent redirect) or 302 (temporary redirect) for requests targeting https://www.uncox.com/, with the URL address to redirect to. You can mirror this process in your Java code, to follow the redirect chain until you get a result code different from 301/302. It's not a foolproof process, and requires your code to have access to the internet, but thats the only way to get a hold on this information in real-time.

EDIT: include the HTTP code 303 (see other) to the list. Either way, it's explained in a good detail in the duplicate question.

Alex Savitsky
  • 2,306
  • 5
  • 24
  • 30
  • But when I print the reponse code, server returns 200. Not 300+ – Hadi Jan 19 '18 at 18:55
  • @Hadi check the answers to the linked question. Basically, if you use `HttpURLConnection`, call `setInstanceFollowRedirects(false)`, or it will follow 30x codes automatically. Also check amobiz's answer there, for an alternative (and, IMHO, beautiful) solution – Alex Savitsky Jan 19 '18 at 19:00
  • Ok, i'll try that. Thank you so much. – Hadi Jan 19 '18 at 19:12