我有一个Web服务,想在我的WebService API链接中通过Flutter Dart json发布数据
答案 0 :(得分:1)
您需要进一步说明API和要发送的内容。这是HTTP client library
中的一个简单示例import 'package:http/http.dart' as http;
var url = "http://example.com/whatsit/create";
http.post(url, body: {"name": "doodle", "color": "blue"})
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
http.read("http://example.com/foobar.txt").then(print);
答案 1 :(得分:0)
能否请您提供有关API的更多详细信息?
假设您的API像这样http://localhost:3000
您可以按照以下要求进行请求
Future<String> create(String text) async {
HttpClient client = new HttpClient();
try {
HttpClientRequest req = await client.post('localhost', 3000, '/');
req.headers.contentType = new ContentType("application", "json", charset: "utf-8");
req.write('{"key":"value"}');
HttpClientResponse res = await req.close();
if (res.statusCode == HttpStatus.CREATED) return await res.transform(UTF8.decoder).join();
else throw('Http Error: ${res.statusCode}');
} catch (exception) {
throw(exception.toString());
}
}
OR
如果您想发布一个Map(通过您拥有的json创建),则可以使用http
包。 https://pub.dartlang.org/packages/http
将“ package:http / http.dart”导入为http;
String url = "http://example.com/whatsit/create";
http.post(url, body: {"name": "doodle", "color": "blue"})
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
答案 2 :(得分:0)
我建议使用此软件包dio package
发布帖子会像这样:
Future<List> postDataFromURL_list(String url, Map map) async {
// TODO: implement postDataFromURL_list
Response response;
Dio dio = new Dio();
FormData formData = new FormData.from(map);
response = await dio.post(url, data: formData);
}
答案 3 :(得分:0)
对于REST API调用,我更喜欢使用名为Dio的库。使用Dio进行GET,POST,PUT,DELETE等调用的方法太简单了。
例如
import 'package:dio/dio.dart';
//Now like this
void _makeApiCall() async {
Dio dio = new Dio();
Response apiResponse = await dio.get('${YOUR URL}?id=$id'); //Where id is just a parameter in GET api call
print(apiResponse.data.toString());
}
如果您要进行POST调用,并且需要发送表单数据,就像这样
void _makeApiCall() async {
Dio dio = new Dio();
FormData formData = FromData.from({
name : "name",
password: "your password",
}); // where name and password are api parameters
Response apiResponse = await dio.post('${YOUR URL}', data: formData);
print(apiResponse.data.toString());
}
此外,您可以将接收到的数据映射到所谓的POJO中,以更好地处理和使用。 如果您想知道如何将数据映射到POJO(对象)中,请告诉我。