-3

Error:

Cannot access the body fields of a Request without content-type "application/x-www-form-urlencoded"

I have tried the best I can but still I cannot make a PUT HTTP Request because of this error.

enter image description here

I have also tried this:

headers: {'Content-Type': 'application/x-www-form-urlencoded'},

And it still it couldn't work.

Here is the code:

RaisedButton(
                            padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                            color: Colors.green,
                            child: Text(
                              "Submit and Validate",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            onPressed: () async {
                              // widget.stockoid
                              var jsonbody = {
                                "oid": mainStockid,
                                "modifiedBy": userData['UserName'],
                                "modifiedOn": DateTime.now().toString(),
                                "submitted": true,
                                "submittedOn": DateTime.now().toString(),
                                "submittedBy": userData['UserName'].toString(),
                              };
                              for (Products i in selectedProducts) {
                                print('${i.oid.toString()} itemid');
                                //i.oid.toString(),
                                var stockupdate = {
                                  "oid": i.oid,
                                  "unitInStock": i.itemqty,
                                  "modifiedBy": userData['UserName'].toString(),
                                  "modifiedOn": DateTime.now().toString(),
                                };
                                
                               //But I could print this data on the console 
                               print(
                                    '${i.oid}, ${i.itemqty.toString()},${userData['UserName']}, 
                                ${DateTime.now().toString()} ploo');
                                await http
                                    .put(
                                        "http://api.ergagro.com:112/StockItem/UpdateStockItem",
                                        headers: {
                                          'Content-Type': 'application/json'
                                        },
                                        body: jsonEncode(stockupdate))
                                  //The value returns 404 witht that error  
                                  .then((value) {
                                  print(value.statusCode);
                                });
                              }
                              await http
                                  .put(
                                      'http://api.ergagro.com:112/SubmitDailyStockTaking',
                                      headers: {
                                        'Content-Type': 'application/json'
                                      },
                                      body: jsonEncode(jsonbody))
                                  .then((value) {
                                print('${value.statusCode} subb');
                              });
                              Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (context) =>
                                          StartScanPage(widget.dcOid)));
                              //Send to API
                            },
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(300),
                            ),
                          ),
halfer
  • 19,824
  • 17
  • 99
  • 186
jonah rimsy
  • 351
  • 1
  • 5
  • 25
  • Isn't this the same [as your previous question](https://stackoverflow.com/questions/63074190/cannot-access-the-body-fields-of-a-request-without-content-type-flutter)? – halfer Jul 28 '20 at 08:53

1 Answers1

1

You should pass header object like below example:

  // set up PUT request arguments
  String url = 'http://api.ergagro.com:112/SubmitDailyStockTaking';
  Map<String, String> headers = {
      "Content-type": "application/json"
  };
  String json = jsonEncode(stockupdate);  
  
  // make PUT request
  Response response = await put(url, headers: headers, body: json);  
  ...

Update:

The input parameter of "oid" and "unitInStock" must be an integer data typed.
For better understanding,

change below code:

var stockupdate = {
      "oid": i.oid,
      "unitInStock": i.itemqty,
      "modifiedBy": userData['UserName'].toString(),
      "modifiedOn": DateTime.now().toString(),
};

with below one:

var stockupdate = {
          "oid": 123,
          "unitInStock": 2,
          "modifiedBy": "UserName",
          "modifiedOn": DateTime.now().toString(),
    };

or relevant datatype based values (integer).

Sanket Vekariya
  • 2,848
  • 3
  • 12
  • 34
  • Hello, @SanketVekariya the endpoint is not **SubmitDailyStockTaking** but this **StockItem/UpdateStockItem** I tried the example above but it still didn't work sir – jonah rimsy Jul 27 '20 at 12:01
  • May I know what is the purpose of for loop in code? Mean what you are exactly tring to achieve? – Sanket Vekariya Jul 27 '20 at 12:08
  • Ok, @SanketVekariya the loop updates items to the database. the items could be one or more. – jonah rimsy Jul 27 '20 at 12:23
  • The reason is your "oid" and "unitInStock" is int type of data and you must be passing something different than this datatype. I have passed this mentioned data type with these parameters and getting response 200. Kindly check the datatype, please! – Sanket Vekariya Jul 27 '20 at 12:40
  • ok @SanketVekariya thank you to let me check out you used integers for the two or strings, please. Can I see what you did so if it works I mark you, sir? – jonah rimsy Jul 27 '20 at 12:45
  • {"StatusCode":200,"Message":"Stock Successfully Submitted!","Success":true,"Stock":{"Oid":123,"CreatedBy":"johndoh","CreatedOn":"2020-07-24T12:29:15.927","ModifiedBy":null,"ModifiedOn":null,"Season":null,"SeasonTitle":null,"Anchor":11,"AnchorName":"MAIZE ASSOCIATION OF NIGERIA","AnchorAcronym":"MAAN","DistributionCentre":13,"DistributionCentreName":"Oturkpo Centre (Zone C)","Agent":"John Doh","StateCoordinator":"Godwin Obute","StockDate":"2020-07-24T06:04:23.217","TransId":"20200724122915927","StateCoordinatorId":"38","AgentId":"57", – Sanket Vekariya Jul 27 '20 at 12:47
  • kindly check out the update section in the solution. – Sanket Vekariya Jul 27 '20 at 12:57
  • OK please let me try it out sir thank you very much @SanketVekariya – jonah rimsy Jul 27 '20 at 13:24
  • Hello @SanketVekariya this endpoint **http://api.ergagro.com:112/SubmitDailyStockTaking** is working already the problem I have is this with this endpoint endpoint **http://api.ergagro.com:112/SubmitDailyStockTaking** I tried it on this endpoint with the exact steps you provided but sir. – jonah rimsy Jul 27 '20 at 14:54
  • Thank u very much the problem was not with the code at all it was with with the url. but thank u very much – jonah rimsy Jul 27 '20 at 22:54