Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to scan for all URLs in redirects from a given link or button?

Say I open a webpage on a Flutter application and I tap on a link or I paste a link into the app, how do I save all the URLs that the website goes to from there, instead of opening the page, but going through each URL in the background. Preferebly I want to save those URLs in a List.

Is such a thing possible?

Example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

www.google.com —> Clicks on First Result

This goes through about 4 URL changes and ends in the final 5th URL of
the desired webpage.

I want to store all 5 URLS in a List without making the user see any
webpages.

>Solution :

As i can understand your question, you can simple make a GET request to the initial URL using the get method of the http package. Check the status code of the response. If it is 301 Moved Permanently or 302 Found, the response will include a location header that specifies the new URL to which the client should redirect make a GET request to the new URL, and repeat the process.. Repeat this process until you reach a URL with a status code other than 301 Moved Permanently or 302 Found, or until you reach a maximum number of redirects.

import 'package:http/http.dart' as http;

List<String> getRedirectChain(String url) {
  List<String> redirectChain = [url];
  while (true) {

    http.Response response = await http.get(url); /// <-- make HTTP request

    // Check the status code of the response
    if (response.statusCode == 301 || response.statusCode == 302) {
      String newUrl = response.headers['location'];
      redirectChain.add(newUrl);
      url = newUrl;
    } else {
       break;
    }
  }
  return redirectChain;
}

That’s the approach I used for my project. let me know. If this help please upvote and accept my answer. Thanks 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading