flutter - 在flutter中编写http post请求的方法
问题描述
我正在编写一个用于酒店注册的应用程序,我正在发送如下的帖子请求
checkNetworkConnection
只是检查设备上是否有活动连接,如果它是真的,那么我正在调用postFormData
方法
Future<dynamic> checkNetworkConnection() async {
try {
final result = await InternetAddress.lookup("www.google.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
postFormData().then((val) {
if (jsonDecode(val.body)[0]["response"] == "false") {
setState(() {
isLoading = false;
//isAbsorbing = false;
});
print(val.body);
print("something went wrong");
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text("hello"),
content: Text("something went wrong"),
),
);
} else if (jsonDecode(val.body)[0]["response"] == "true") {
setState(() {
isLoading = false;
//isAbsorbing = false;
});
print(val.body);
print("hotel added successfully");
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text("Hotel Added Successfully"),
content: Text("Hey there! Welcome to j1"),
));
}
}).catchError((error) {
setState(() {
isLoading = false;
});
showDialog(
context: context,
builder: (_) {
return new AlertDialog(
title: Text("error!"), content: Text(error.toString()));
});
});
}
} on SocketException catch (_) {
setState(() {
isLoading = false;
});
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text(
"Connection Error !",
style: TextStyle(
color: Colors.redAccent, fontWeight: FontWeight.bold),
),
content: Text("Check your internet connection !"),
));
}
}
postFormData
方法如下
Future<dynamic> postFormData() async {
//there are declarations for parent and headers I just excluded them because they were quite a lot ^_^ !
final response = await http
.post("https://thej1.app/apiDataReq",
body: parent, headers: httpHeaders)
.then((val) => val)
.timeout(Duration(seconds: 5))
.catchError((_) {
setState(() {
isLoading = false;
});
showDialog(
context: context,
builder: (_) =>
new AlertDialog(title: Text("error"), content: Text("error")));
});
return response;
}
还有其他做同样的事情吗?和未来的建设者一样?
我的响应主体有一个结构,以便我可以创建响应模型。但我无法在未来的构建器中实现它。我也想要捕获异常和超时错误。
提前致谢
解决方案
推荐阅读
- r - 计算 R 中每一列的出现次数
- airflow - 如何解码气流表 dag_run 列 conf 值
- python - 如何更改python模块中的函数?
- c - 为什么我的线性代数 C 程序会因非方阵而失败?
- json - 如何检索本地 json 数据以将其显示在谷歌地图上?
- azure - 来自联合 Azure 租户的用户可以使用相同的电子邮件向我的 Azure 租户注册吗?
- azure-functions - Azure 函数消耗计划超时
- .net - 在 .net 中使用 SAML 断言准备 Soap 服务
- python - 将数据框中的特定单元格拆分为值列表
- r - 在 r 中置换一列 1000 次