简体   繁体   English

Dart (flutter): Http 请求好像没有执行

[英]Dart (flutter): Http requests seem not to execute

I'm trying to make a simple HTTP-head request within a Future.我正在尝试在 Future 中发出一个简单的 HTTP-head 请求。 However, for some reason, the request is not executed.但是,由于某种原因,请求没有被执行。 This is my current code:这是我当前的代码:

  Future<int> logIn({
    required String username,
    required String password,
  }) async {
    print("logIn started");
    final base64creds = base64.encode(utf8.encode(username + ":" + password));
    print(base64creds);
    Map<String, String> headers = new HashMap();
    headers.putIfAbsent("credentials", () => base64creds);
    print(headers.toString());
    var response = await http.head(
      Uri.parse("http://localhost:8060/users/validateLogin/"),
      headers: headers,
    );

    print(response.statusCode);

    return response.statusCode;
  }

The console output of the printout looks like this:打印输出的控制台 output 如下所示:

logIn started
MTph
{credentials: MTph}

The Future is executed in a try-catch block. Future 在 try-catch 块中执行。 This block always ends up in the catch, means the request either fails or is never executed.这个块总是在捕获中结束,意味着请求要么失败要么永远不会执行。 I can't figure out what I am doing wrong and hope you can help me!我不知道我做错了什么,希望你能帮助我!

I have just solved this issue.我刚刚解决了这个问题。 The problem here war that the repsonse cannot be a var but must be of type http.Response .这里的问题是repsonse不能是var但必须是http.Response类型。 So the code would look like this:所以代码看起来像这样:

  Future<int> logIn({
    required String username,
    required String password,
  }) async {
    final base64creds = base64.encode(utf8.encode(username + ":" + password));
    Map<String, String> headers = new HashMap();
    headers.putIfAbsent("credentials", () => base64creds);
    http.Response response = await http.head(
      Uri.parse(
          "https://pius-server-dev.eu-gb.mybluemix.net/users/validateLogin"),
      headers: headers,
    );
    return response.statusCode;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM