Get URL of a http get request in flutter app

可紊 提交于 2021-01-28 18:44:17

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/54831648/get-url-of-a-http-get-request-in-flutter-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!