未处理的异常:错误状态:无法设置内容类型为“ application / json”的请求的正文字段,并且http帖子中出现415错误

问题描述 投票:0回答:1

我正在发送一个http发布请求,我需要传递4个变量(值)名称,移动电话号码,纬度和经度,但是我收到一个错误,无法设置内容类型为“ application / json”的请求的正文字段如果我删除了"content-type" : "application/json",那么它将显示错误415状态代码。

Register.dart

class Register extends StatefulWidget {
  @override
  _RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
  final _formKey = GlobalKey<FormState>();
  static String _locationMessage1 = "";
  static String _locationMessage2 = "";
  String value;
  final TextEditingController nameController=TextEditingController();
  final TextEditingController mobileController=TextEditingController();
  void _getCurrentLocation() async{
    final position=await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
    print(position);
    setState(() {
      _locationMessage1="${position.latitude}";
      _locationMessage2="${position.longitude}";
    });
  }
  GoogleMapController _controller;
  Position position;
  Future<UserRegister> createUser(String name,String mobile,String latitude,String longitude) async{
    final String apiUrl="http://cashback.us-east-2.elasticbeanstalk.com/user/register";
    final response=await http.post(apiUrl,body: json.encode({
      "name": name,
      "mobile": mobile,
      "lat": latitude,
      "lng": longitude,
    }),headers: {"content-type" : "application/json",
      "Accept": "application/json",}
    );
    if(response.statusCode==201){
      final responseString=response.body;
      return userRegisterFromJson(responseString);
    }else{
      return null;
    }
  }
  UserRegister _userRegister;
  @override
  Widget build(BuildContext context) {
    return PlatformScaffold(
      body: Form(
        key: _formKey,
        child: ListView(
          children: <Widget>[
            Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    GestureDetector(
                      onTap: (){
                        Navigator.pop(context);
                      },
                      child: Icon(
                        Icons.close,
                        size: 40.0,
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Center(
                    child: new ListView(
                      shrinkWrap: true,
                      children: <Widget>[
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(top: 20.0),
                              child: TextFormField(
                                keyboardType: TextInputType.text,
                                controller: nameController,
                                style: new TextStyle(color: Colors.black),
                                validator: (val)=>val.length==0?"Enter Your Name":null,
                                decoration: new InputDecoration(
                                  enabledBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.blue),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.blue),
                                  ),
                                  focusedErrorBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.redAccent),
                                  ),
                                  hintText: "Name",
                                  fillColor: Colors.grey[200],
                                  filled: true,
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 20.0),
                              child: TextFormField(
                                keyboardType: TextInputType.phone,
                                controller: mobileController,
                                onChanged: (text){
                                  value=text;
                                },
                                style: new TextStyle(color: Colors.black),
                                validator: (val)=>val.length==0?"Enter Your Mobile Number":null,
                                decoration: new InputDecoration(
                                  enabledBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.blue),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.blue),
                                  ),
                                  focusedErrorBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.redAccent),
                                  ),
                                  hintText: "Mobile Number",
                                  fillColor: Colors.grey[200],
                                  filled: true,
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 20.0),
                              child: PlatformButton(
                                onPressed: () {
                                  _getCurrentLocation();
                                },
                                child: Text('Get Current Location',style: TextStyle(color: Colors.white),),
                                  androidFlat: (_) => MaterialFlatButtonData(
                                      color: Colors.cyan
                                  ),
                                  ios: (_) => CupertinoButtonData(
                                      color: Colors.cyan
                                  )
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 10.0),
                              child: Text(
                                _locationMessage1,
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 10.0),
                              child: Text(
                                _locationMessage2,
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 15.0),
                              child: Center(
                                child: PlatformButton(
                                  onPressed: () async{
                                    final String name=nameController.text;
                                    final String mobile=mobileController.text;
                                    final UserRegister userRegister=await createUser(name, mobile, _locationMessage1, _locationMessage2);
                                    setState(() {
                                      _userRegister=userRegister;
                                    });
                                  },
                                  child: Text('Register',style: TextStyle(color: Colors.white),),
                                    androidFlat: (_) => MaterialFlatButtonData(
                                        color: Colors.cyan
                                    ),
                                    ios: (_) => CupertinoButtonData(
                                        color: Colors.cyan
                                    )
                                ),
                              ),
                            ),
                            _userRegister==null?Container():
                            Center(child: Text("${_userRegister.user.name} ${_userRegister.user.mobile} ${_userRegister.user.lat} ${_userRegister.user.lng}")),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

UserRegister.dart

UserRegister userRegisterFromJson(String str) => UserRegister.fromJson(json.decode(str));

String userRegisterToJson(UserRegister data) => json.encode(data.toJson());

class UserRegister {
  User user;
  Driver driver;

  UserRegister({
    this.user,
    this.driver,
  });

  factory UserRegister.fromJson(Map<String, dynamic> json) => UserRegister(
    user: User.fromJson(json["user"]),
    driver: Driver.fromJson(json["driver"]),
  );

  Map<String, dynamic> toJson() => {
    "user": user.toJson(),
    "driver": driver.toJson(),
  };
}

class Driver {
  int driverId;
  User user;
  String deliveryCount;
  String totalMoney;
  String totalMoneyWithdraw;
  int creationDate;
  int updateDate;

  Driver({
    this.driverId,
    this.user,
    this.deliveryCount,
    this.totalMoney,
    this.totalMoneyWithdraw,
    this.creationDate,
    this.updateDate,
  });

  factory Driver.fromJson(Map<String, dynamic> json) => Driver(
    driverId: json["driverId"],
    user: User.fromJson(json["user"]),
    deliveryCount: json["deliveryCount"],
    totalMoney: json["totalMoney"],
    totalMoneyWithdraw: json["totalMoneyWithdraw"],
    creationDate: json["creationDate"],
    updateDate: json["updateDate"],
  );

  Map<String, dynamic> toJson() => {
    "driverId": driverId,
    "user": user.toJson(),
    "deliveryCount": deliveryCount,
    "totalMoney": totalMoney,
    "totalMoneyWithdraw": totalMoneyWithdraw,
    "creationDate": creationDate,
    "updateDate": updateDate,
  };
}

class User {
  int userId;
  String name;
  String mobile;
  String token;
  int lat;
  int lng;
  bool isDriver;
  bool admin;
  bool mobileVaild;
  bool isLock;
  bool isPanding;
  int creationdate;

  User({
    this.userId,
    this.name,
    this.mobile,
    this.token,
    this.lat,
    this.lng,
    this.isDriver,
    this.admin,
    this.mobileVaild,
    this.isLock,
    this.isPanding,
    this.creationdate,
  });

  factory User.fromJson(Map<String, dynamic> json) => User(
    userId: json["userId"],
    name: json["name"],
    mobile: json["mobile"],
    token: json["token"],
    lat: json["lat"],
    lng: json["lng"],
    isDriver: json["isDriver"],
    admin: json["admin"],
    mobileVaild: json["mobileVaild"],
    isLock: json["isLock"],
    isPanding: json["isPanding"],
    creationdate: json["creationdate"],
  );

  Map<String, dynamic> toJson() => {
    "userId": userId,
    "name": name,
    "mobile": mobile,
    "token": token,
    "lat": lat,
    "lng": lng,
    "isDriver": isDriver,
    "admin": admin,
    "mobileVaild": mobileVaild,
    "isLock": isLock,
    "isPanding": isPanding,
    "creationdate": creationdate,
  };
}
http flutter dart
1个回答
0
投票

为如下所示的帖子正文传递json编码器的地图。

© www.soinside.com 2019 - 2024. All rights reserved.