首页 > 解决方案 > 在 Flutter 应用中获取 http get 请求的 URL

问题描述

我正在尝试获取以下获取请求的 URL;

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');
}
}

我得到一个 200 的状态码。

有任何想法吗?

澄清一下,当您在浏览器中输入 url 时,它会将我带到一个带有 url 的页面,其中包含代码。我正在尝试提取该代码。

标签: httpurldartgetflutter

解决方案


followRedirects默认情况true下,我还没有找到一种方法来获取它重定向到这种方式的 URL。

设置followRedirects = false在标头中返回新地址location

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

如果你想获取重定向地址的内容,你可以发送一个新的请求,带有来自location或只使用默认 ( followRedirects = true)的 URL


推荐阅读