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
)
Author by
Darran Mullen
Updated on December 09, 2022Comments
-
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 about 5 yearscan you add some of your logs
-
Darran Mullen about 5 yearswhat would you like to see?
-
Günter Zöchbauer about 5 yearsAre you using HTTP from
dart:io
or frompackage:http
? -
Darran Mullen about 5 yearsimport 'package:http/http.dart' as http;
-
-
Darran Mullen about 5 yearsis redirect is false
-
Günter Zöchbauer about 5 yearsWhat is the response code? Is the
location
header set? -
Günter Zöchbauer about 5 yearsIs it a public URL that I can test myself with?
-
Darran Mullen about 5 yearsresponse.statusCode = 200, and no the location header is not set
-
Darran Mullen about 5 yearsits 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 about 5 yearsI updated my answer. The URL redirects from
wikipedia.net
towikipedia.org