首页 > 解决方案 > 我无法在颤动中对特定的 url 进行 REST api 调用

问题描述

我无法在此 URL 上进行简单的 get 调用 >>>

http://54.254.255.202:8080/user/status/S5454523D/ST. 

这个 url 适用于任何其他像 postman、chrome、android 或 react-native 这样的东西。我特别不知道它仅在 20 次尝试中的 1 次中起作用的原因。在日志中我得到这样的东西

E/flutter: [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
Connection closed before full header was received

这也是我用来尝试这个简单的获取请求的代码

Future<dynamic> getStatus() async {
var res;
String url = "http://54.254.255.202:8080/user/status/S5454523D/ST";
print(url);
var response = await http.get(
    Uri.encodeFull(url),
    headers: {"Accept": "application/json"}
    ).catchError((error){
      print(error);
}).whenComplete((){
  print("completed");
});
print(response);
return res;
}

我使用的任何其他 URL 都运行良好。请帮助。

标签: dartflutter

解决方案


Try simplifying your getStatus method. This version seems to reliably return the decoded json.

Future<Map> getStatus() async {
  try {
    Response r = await http.get(
      'http://54.254.255.202:8080/user/status/S5454523D/ST',
      headers: {
        'Accept': 'application/json',
      },
    );
    return json.decode(r.body);
  } catch (e) {
    return {'error': e.toString()};
  }
}

main() async {
  print(await getStatus());
}

推荐阅读