Get URL of a http get request in flutter app

4,665

followRedirects is true by default and I haven't found a way to get the URL it redirects to this way.

Setting followRedirects = false returns the new address in the location header.

  final url = 'http://wikipedia.net';
  final client = http.Client();
  final request = new http.Request('GET', Uri.parse(url))
    ..followRedirects = false;
  final response = await client.send(request);

  print(response.headers['location']);
  print(response.statusCode);

If you want to fetch the content of the redirect address, you can send a new request with the URL from location or just with the default (followRedirects = true)

Share:
4,665
Darran Mullen
Author by

Darran Mullen

Updated on December 09, 2022

Comments

  • Darran Mullen
    Darran Mullen over 1 year

    I am trying to get the URL of the following get request;

    String url = ['url_here'];
    Future<Post> fetchPost() async {
    final response = await http.get(url);
    
    if (response.statusCode == 200) {
    return Post.fromJson(json.decode(response.body));
    } else {
    throw Exception('Failed to load post');
    }
    }
    

    I get a statuscode of 200.

    Any ideas?

    To clarify, When you enter the url in a browser it brings me to a page with a url that has a code in it. I am trying to extract that code.

    • Sami Kanafani
      Sami Kanafani about 5 years
      can you add some of your logs
    • Darran Mullen
      Darran Mullen about 5 years
      what would you like to see?
    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      Are you using HTTP from dart:io or from package:http?
    • Darran Mullen
      Darran Mullen about 5 years
      import 'package:http/http.dart' as http;
  • Darran Mullen
    Darran Mullen about 5 years
    is redirect is false
  • Günter Zöchbauer
    Günter Zöchbauer about 5 years
    What is the response code? Is the location header set?
  • Günter Zöchbauer
    Günter Zöchbauer about 5 years
    Is it a public URL that I can test myself with?
  • Darran Mullen
    Darran Mullen about 5 years
    response.statusCode = 200, and no the location header is not set
  • Darran Mullen
    Darran Mullen about 5 years
    its not public. i'm trying to connect fitbit to my app. on their OAuth 2.0 tutorial page they build the url with clientsecret etc. they say: Copy and paste the code that you can find in the redirect URL after the user has clicked the "allow" button. Example: localhost:8888/…, the code you need to paste from that example is 7b64c4b088b9c841d15bcac15d4aa7433d35af3e. Don't include the “#_=_”.
  • Günter Zöchbauer
    Günter Zöchbauer about 5 years
    I updated my answer. The URL redirects from wikipedia.net to wikipedia.org