当我通过将curl转换为JSON在FLutter中发送POST请求时遇到问题。我是Flutter的新手,我正在尝试将数据发送到互联网。这是我的卷发:
curl -X POST http://my-server/api/order \
-d api_key='My API key' \
-d phone='Mobile Phone' \
-d street='Street Name'\
-d moderation_required=no
这是我编写的Flutter代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'model/orderTaxi_model.dart';
import 'package:http/http.dart' as http;
Future<Data> createOrder(String street) async {
final http.Response response = await http.post(
'http://XXX.XXX.XXX.XXX/api/order',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'api_key': 'My api Key',
'phone': '1234',
'street': street,
'moderation_required': 'yes',
}),
);
if (response.statusCode == 201) {
return Data.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to order Taxi');
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _controller = TextEditingController();
Future<Data> _futureOrder;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Post Request'),
),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: (_futureOrder == null)
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _controller,
decoration: InputDecoration(hintText: 'Enter Street'),
),
RaisedButton(
child: Text('Place Order'),
onPressed: () {
setState(() {
_futureOrder = createOrder(_controller.text);
});
},
)
],
)
: FutureBuilder<Data>(
future: _futureOrder,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.phone);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return CircularProgressIndicator();
},
)),
);
}
}
作为参考,我正在使用此网站https://flutter.dev/docs/cookbook/networking/send-data。 如果有人可以帮助我解决此问题,我将不胜感激。我不知道我在哪里做错。也许我的错误是在我转换HTTP时对dart对象的响应?
答案 0 :(得分:0)
在curl -d
中表示URL编码形式参数。在Dart代码中,您发送的是JSON字符串。
删除所有对JSON的引用,并让http客户端对表单进行编码(如果您传入Map<String, String>
,它将执行此操作。
final http.Response response = await http.post(
'http://xxx.yyy/api/order',
headers: <String, String>{
// no! let http set the content type itself -'Content-Type': 'application/json; charset=UTF-8',
},
body: <String, String>{
'api_key': 'My api Key',
'phone': '1234',
'street': street,
'moderation_required': 'yes',
},
);