1

为了在移动应用程序上使用 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;
}

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

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

4

1 回答 1

1

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

解决方案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;
于 2019-10-16T18:06:43.430 回答