Home > Software engineering >  How to scan for all URLs in redirects from a given link or button?
How to scan for all URLs in redirects from a given link or button?

Time:12-31

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:

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.

CodePudding user response:

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 :)

  • Related