【问题标题】:How to get query params in a server request in flutter?如何在颤动的服务器请求中获取查询参数?
【发布时间】:2019-10-17 02:06:43
【问题描述】:

为了在移动应用上使用 Imgur 进行身份验证,我决定在端口 8585 上生成一个 http 服务器以完成 oauth 流程。读取请求并写入响应,但我无法从 url 访问查询参数。

我已经尝试使用 uri.queryparameters["access_token"],但返回 null。

服务器生成如下:

Future<Stream<String>> _server() async {
  final StreamController<String> onCode = new StreamController();
  HttpServer server =
  await HttpServer.bind(InternetAddress.loopbackIPv4, 8585);
  server.listen((HttpRequest request) async {
    print(request.uri.hashCode);
    final String accessToken = request.uri.queryParameters["access_token"];


    request.response
      ..statusCode = 200
      ..headers.set("Content-Type", ContentType.html.mimeType)
      ..write("<html><h1>You can now close this window</h1></html>");
    await request.response.close();
    await server.close(force: true);
    onCode.add(accessToken);
    await onCode.close();
  });
  return onCode.stream;
}

服务器获取的 url 是这样的:http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here

谁能帮帮我?我已经坚持了整整两天了!

【问题讨论】:

  • 如果您遇到问题,请使用您能想到的最简单的方法来解决它。在这种情况下,您可以使用 string.indexOf('access_token')string.substring 来获取令牌。
  • @aligator 问题是我无法获得完整路径;我能想到的所有获取 uri 路径的方法都以“回调”结尾。

标签: flutter dart-server


【解决方案1】:

它返回 null 因为查询参数以? 开头,但在此链接中,查询参数前有一个#,将其替换为? 确实可以解决问题。

解决方案 1:

 var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
 var newUri = Uri(query: uri.toString().substring(uri.toString().indexOf('#')+1));
 print(newUri.queryParameters['access_token']) // your_token_here;

解决方案 2:

  var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
  var newUri = Uri.parse(uri.toString().replaceFirst('#', '?'));
  print(newUri.queryParameters['access_token']) // your_token_here;

【讨论】:

  • 感谢您的回复!问题是我得到一个 HttpRequest 并且我无法得到完整的 uri 字符串。如果我打印 request.uri.toString() 我只会得到“/callback”而没有后面的查询。关于如何获得完整路径的任何想法?
猜你喜欢
  • 2021-06-28
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多