cannot access the body fields of a Request without content-type - Flutter

↘锁芯ラ 提交于 2021-01-29 06:38:29

问题


I am having an issue making an HTTP PUT requests in a flutter. I can print the data on the console but when I tried to parse it to the endpoint that performs a PUT request, it return a response of 404 please can anyone help me?

and this is the message: cannot access the body fields of a Request without content-type

"application/x-www-form-urlencoded" Here is the actual problem:

 for (Products i in selectedProducts) {
                                var stockupdate = {
                                  
                                  "oid": i.oid, // I can't get the oid here
                                  "unitInStock": i.itemqty,
                                  "modifiedBy": userData['UserName'].toString(),
                                  "modifiedOn": DateTime.now().toString(),
                                };
                                // but on the console, the oid is showing.
                                print(
                                    '${i.oid}, ${i.itemqty.toString()},${userData['UserName']},2020-07-06T07:19:01.492Z ploo');
                                await http
                                    .put(
                                        "http://api.ergagro.com:112/StockItem/UpdateStockItem",
                                        headers: {
                                          'Content-Type': 'application/json'
                                        },
                                        body: jsonEncode(stockupdate))
                                    .then((value) {
                                  print(value.statusCode);
                                });
                              }

Here is the endpoint that gets the products for me:


  void GeneratekDailyStock() async {
    //http: //api.ergagro.com:112/GenerateDailyStockTaking?userId=b6caf34c-a425-4710-a3ee-aa22a382882a&agentOid=57&dcOid=11
    final response = await http.get(
        'http://api.ergagro.com:112/GenerateDailyStockTaking?userId=${widget.userid}&agentOid=${widget.oid}&dcOid=${widget.dcOid}');
    print('${response.statusCode} Generated');
    if (response.statusCode == 200) {
      final jsonStatus = jsonDecode(response.body);
      var stock = jsonStatus['Stock'];
      // You can call the id of your own stock here.
      mainStockid = stock['Oid'].toString();

      List<dynamic> StockItems = stock['StockItems'];
      for (var i in StockItems) {
        print('${i['Oid'].toString()} iodd');
        setState(() {
          products.add(Products(
            
            oid: i['Oid'], //this is the Id I am looking for
            count: i['ItemType'].toString(),
            name: i['ItemName'],
            itemqty: i['Stock'].toString(),
            measuringunit: i['Unit'],
          ));
        });
      }
    } else {
      throw Exception();
    }
  }


Here's the overall view of the products and the button that submits the Put request

   // Form widget initialization
            Container(
              margin: EdgeInsets.all(24),
              child: Form(
                key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    // form was here
                    Divider(),
                    SizedBox(height: 20),
                    SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: DataTable(
                          columns: [
                            DataColumn(
                              label: Text('ID'),
                            ),
                            DataColumn(
                              label: Text('Items'),
                            ),
                            DataColumn(
                              label: Text('Quantities'),
                            ),
                            // Lets add one more column to show a delete button
                            DataColumn(
                              label: Text('Update'),
                            )
                          ],
                          rows: selectedProducts
                              .map(
                                (product) => DataRow(
                                    selected:
                                        selectedProducts.contains(product),
                                    cells: [
                                      DataCell(
                                        Text(product.count),
                                        onTap: () {
                                          print('Selected ${product.count}');
                                        },
                                      ),
                                      DataCell(
                                        Text(product.name),
                                        onTap: () {
                                          print('Selected ${product.name}');
                                        },
                                      ),
                                      DataCell(
                                        Text(product.itemqty),
                                        onTap: () {
                                          print('Selected ${product.itemqty}');
                                        },
                                      ),
                                      DataCell(
                                        Text('Edit'),
                                        onTap: () {
                                          setState(() {
                                            _isUpdate = true;
                                          });
                                        },
                                        showEditIcon: true,
                                      ),
                                    ]),
                              )
                              .toList(),
                        ),
                      ),
                    ),
                    SizedBox(height: 20),
                    Container(
                      child: Row(
                        children: <Widget>[
                          
                          SizedBox(width: 10),
                          
                          RaisedButton(
                            padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                            color: Colors.orangeAccent,
                            child: Text(
                              "Submit and Close",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            onPressed: () async {
                              var jsonbody = {
                                "oid": mainStockid,
                                "modifiedBy": userData['UserName'],
                                "modifiedOn": DateTime.now().toString(),
                                "submitted": false.toString(),
                                "submittedOn": DateTime.now().toString(),
                                "submittedBy": userData['UserName']
                              };
                              for (Products i in selectedProducts) {
                                var stockupdate = {
                                  
                                  "oid": i.oid, // I can't get the oid here
                                  "unitInStock": i.itemqty,
                                  "modifiedBy": userData['UserName'].toString(),
                                  "modifiedOn": DateTime.now().toString(),
                                };
                                // but on the console, the oid is showing.
                                print(
                                    '${i.oid}, ${i.itemqty.toString()},${userData['UserName']},2020-07-06T07:19:01.492Z ploo');
                                await http
                                    .put(
                                        "http://api.ergagro.com:112/StockItem/UpdateStockItem",
                                        headers: {
                                          'Content-Type': 'application/json'
                                        },
                                        body: jsonEncode(stockupdate))
                                    .then((value) {
                                  print(value.statusCode); //This status code shows 400
                                });
                              }
                              await http
                                  .put(
                                      'http://api.ergagro.com:112/SubmitDailyStockTaking',
                                      headers: {
                                        'Content-Type': 'application/json'
                                      },
                                      body: jsonEncode(jsonbody))
                                  .then((value) {
                                print('${value.statusCode} submitted'); // but this is showing 200
                              });
                              Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (context) => AnchorsPage()));
                            },
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(50),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 30),
                  ],
                ),
              ),
            ),
            // End of form widget Initialization

And here is the Product Model:

class Products {
  var oid;
  String count;
  String name;
  String measuringunit;
  String itemqty;
  Products({this.oid, this.count, this.name, this.itemqty, this.measuringunit});

来源:https://stackoverflow.com/questions/63074190/cannot-access-the-body-fields-of-a-request-without-content-type-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!