Flutter : get the original link of shorten url

1.2k Views Asked by At

I have to fetch some url link, but the link is shorten like "shorturl.at/cpqCE". I want to get the original link url in flutter. How can I do this? in Phph I found this :

function expandShortUrl($url) {
    $headers = get_headers($url, 1);

    return $headers['Location'];
}

// will echo https://deluxeblogtips.com
echo expandShortUrl($url);
2

There are 2 best solutions below

0
Sarmed MQ Berwari On

Thanks to @RandalSchwartz I solved it by using :

getUrl(url) async {
    final client = HttpClient();
    var uri = Uri.parse(url);
    var request = await client.getUrl(uri);
    request.followRedirects = false;
    var response = await request.close();
    while (response.isRedirect) {
      response.drain();
      final location = response.headers.value(HttpHeaders.locationHeader);

      if (location != null) {
        uri = uri.resolve(location);
        request = await client.getUrl(uri);
        // Set the body or headers as desired.

        if (location.toString().contains('https://www.xxxxx.com')) {
          return location.toString();
        }
        request.followRedirects = false;
        response = await request.close();
      }
    }
  }
0
Faisal M On

you can also do it by just sending a normal post request with the short link and you will then get the response which includes the original/full URL. e.g

var uri = Uri.parse(shortUrl);
try {
  var response = await http.post(
    uri,
    headers: {"Accept": 'application/json'},
  );
  // with below code you get the full path of a short url
  String fullPath = response.headers.entries.firstWhere((element) => element.key == "location").value;
  print(fullPath);
} catch (e) {
  print(e);
}

hope this can help your problem.