How to get query params in a server request in flutter?

3k views Asked by At

In order to authenticate with Imgur on a mobile app, I decided to spawn an http server on port 8585 in order to complete the oauth flow. The request is read and a response is written, but I cannot access the queryparameters from the url.

I already tried using uri.queryparameters["access_token"], but null is returned.

the server is spawned as follows:

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

the url the server gets is of the sort: http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here

Can anyone help me? I've been stuck on this for two whole days!

1

There are 1 answers

1
Ali Qanbari On

It returns null because query parameters start with ? at the beginning but in this link, there is a # before the query parameters and replacing it with a ? does solve the problem.

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

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