【发布时间】:2020-06-25 00:42:39
【问题描述】:
我正在 Flutter/Dart 中编写一个客户端 REST,它应该管理来自 REST 服务器(Java 服务器)的一些数据。 如果为 Android 编译,客户端可以正常工作,完全没有问题。 但是当它为 Chrome ( Javascript ) 编译时,会出现很多问题,比如: 当我尝试发出 HTTP PUT 请求时,客户端似乎出现了未知错误,而没有将请求发送到服务器。
奇怪的是,这个问题只在动词 PUT 上,动词 POST 工作正常(但我仍然没有尝试使用 PATCH/DELETE)。 因此,当使用动词 PUT 而不是 POST 时,内部 http 库似乎存在错误。 http:0.10.0
代码如下:
void _sendRequest() async {
try {
print('Send Request : ');
// String url = "http://10.0.2.2:8080/v2/account";
String url = "http://localhost:8080/v2/account";
Map<String, String> headers = new HashMap();
headers['Accept'] = 'application/json';
headers['Content-type'] = 'application/json';
Http.Response response = await Http.put(url,
headers: headers,
body: jsonEncode({
"description": "string",
"id": 25,
"name": "11112",
"password": "seesfs"
}),
encoding: Encoding.getByName('utf-8'));
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}catch(error) {
print("${error?.toString()}");
}
}
如您所见,我使用 Web 客户端时使用 localhost 地址,使用 android VM 时使用 10.0.2.2。 使用 android 编译时相同的代码有效,而 javascript 则无效。 任何想法? 你有遇到同样的问题吗?
下面是示例测试项目:
名称:accounts_client_http 描述:一个新的 Flutter 项目。
版本:1.0.0+1
环境: sdk: ">=2.1.0
依赖: http:^0.12.0+4 扑: sdk:颤动
dev_dependencies: 颤振测试: sdk:颤动
颤动: 使用材料设计:是的
颤振医生来了
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.14.6, on Linux, locale it_IT.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Community Edition (version 2019.3)
[✓] VS Code (version 1.43.0)
[✓] Connected device (2 available)
• No issues found!
【问题讨论】: