2

I have short-url

bit.ly/18SuUzJ

that leads to

stackoverflow.com/

Do you know how to get that url using HTTP Request with Java? I added Unirest to maven dependencies and tried sth like:

    HttpResponse<String> response = Unirest.get("bit.ly/18SuUzJ").asObject(String.class);
    System.out.println(response.getBody());

but I get whole structure of that page, not only url . How to get only url that would work for other bitly short-urls?

AAlechin
  • 31
  • 3

1 Answers1

2

Try this:

final String link = "bit.ly/18SuUzJ";
final URL url = new URL(link);
final HttpURLConnection urlConnection = 
(HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false);

final String location = 
urlConnection.getHeaderField("location");
System.out.println(location);

location will print the complete URL.

Abhay
  • 403
  • 3
  • 12