Flutter: Error: Internal Server Error, Code 500

9,458

Here's the cURL request you say is working in your comment above, formatted a little nicer:

curl -X POST \ 
  URLSample..orSomething \ 
  -H 'Content-Type: application/json' \ 
  -H 'Postman-Token: a3621ffc-f029-4973-b015-c7fea1c2b429' \ 
  -H 'cache-control: no-cache' \ 
  -d '{ "username" : "administrador", "password" : "admin2010" }'

As you can see with the Content-Type header, Postman (and cURL) are telling the server to expect JSON data in the request body. You can also see that JSON payload being sent.

Now looking at your code, we can start to understand why it isn't working. You are not setting the content type header in your request, but more importantly you are not sending JSON.

Here is your request body:

body: {
  "username": user,
  "password": password
},

This is actually a dart Map<String, dynamic>. From the http documentation, this will be encoded into form data, not JSON:

If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.

So to fix your request, we should set the Content-Type header, and do the JSON encoding ourselves. It will end up looking like this:

// we import the convert library to access jsonEncode
import 'dart:convert';

Map<String, dynamic> requestPayload = {
  "username": user,
  "password": password,
};

final response = await http.post(
  Uri.encodeFull("Example End Point login"),
  body: jsonEncode(requestPayload),
  headers: {'Content-Type': 'application/json'},

);
Share:
9,458
isaac cubas
Author by

isaac cubas

Updated on December 12, 2022

Comments

  • isaac cubas
    isaac cubas over 1 year

    When connecting to an endpoint using flutter, it returns error 500, next to an expiration time variable, now this only happens when I send the user name and password, the thing is, with the same information using PostMan the result is code 200 and all the corresponding variables. What could be the problem?

    Use basically flutter in conjunction with Android Studio and postman

    import 'package:flutter/material.dart';
    
    import 'package:http/http.dart' as http;
    import 'dart:async';
    import 'package:loginqr/post_model.dart';
    import 'dart:io';
    import 'package:loginqr/SignIn.dart';
    void main() => runApp(MyApp());
    
    
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            // This is the theme of your applicatio
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'aa',),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      // This widget is the home page of your application. It is stateful, meaning
      // that it has a State object (defined below) that contains fields that affect
      // how it looks.
    
      // This class is the configuration for the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          // This call to setState tells the Flutter framework that something has
          // changed in this State, which causes it to rerun the build method below
          // so that the display can reflect the updated values. If we changed
          // _counter without calling setState(), then the build method would not be
          // called again, and so nothing would appear to happen.
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        // This method is rerun every time setState is called, for instance as done
        // by the _incrementCounter method above.
        //
        // The Flutter framework has been optimized to make rerunning build methods
        // fast, so that you can just rebuild anything that needs updating rather
        // than having to individually change instances of widgets.
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: MyCustomFrom(),
    
    
          // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    }
    
    class MyCustomFrom extends StatefulWidget{
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return MyCustomFromState();
      }
    
    }
    
    
    class MyCustomFromState extends State<MyCustomFrom> {
    
    
      Future<String> getData() async {
    
        final response = await http.post(
            Uri.encodeFull("Example End Point login"),
    
         body: {
    
              "username": user,
              "password": password
            },
    
            );
    
        //application/json
    
    //   print(response.statusCode);
    
        print(response.body);
      //  print(response.toStri()ng());
      }
    
    
    
    
    
      String _deviceid = 'Unknown';
      String user = '';
      String password = '';
    
      TextEditingController controller = new TextEditingController();
      TextEditingController controller2 = new TextEditingController();
    
      @override
      void dispose() {
        controller.dispose();
        controller2.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        final username = TextFormField(
          controller: controller,
          keyboardType: TextInputType.text,
          autofocus: false,
          decoration: InputDecoration(
              hintText: "Username",
              hintStyle: TextStyle(fontSize: 16.0),
              contentPadding: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 10.0),
              border:
              UnderlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
        );
        final password = TextFormField(
          controller: controller2,
          autofocus: false,
          obscureText: true,
          decoration: InputDecoration(
              hintText: "Password",
              hintStyle: TextStyle(fontSize: 16.0),
              contentPadding: EdgeInsets.fromLTRB(20.0, 25.0, 20.0, 10.0),
              border:
              UnderlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
        );
    
        final loginButton = Padding(
          padding: EdgeInsets.symmetric(vertical: 25.0),
          child: Material(
            borderRadius: BorderRadius.circular(30.0),
            shadowColor: Colors.blueAccent.shade100,
            elevation: 10.0,
            child: MaterialButton(
              minWidth: 200.0,
              height: 42.0,
              color: Colors.blueAccent,
              onPressed: (){
    getData();
              },
              child: Text(
                "Login",
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        );
        return Form(
          child: new Center(
            child: ListView(
                padding: EdgeInsets.only(left: 24.0, right: 24.0, top: 10.0),
                children: <Widget>[
                  username,
                  SizedBox(height: 8.0),
                  password,
                  SizedBox(height: 24.0),
                  loginButton
                ]),
          ),
        );
    
      }
    }
    

    using tue code print(response.body); the output is:

    I/flutter (21983): {"timestamp":1563220761561,"status":500,"error":"Internal Server Error","exception":"java.lang.IllegalStateException","message":"java.lang.IllegalStateException: STREAMED","path":"/api/login"}
    

    and using postman tue output is:

    {"access-token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBRE1JTklTVFJBRE9SIiwiZXhwIjoxNTYzMzAwOTE3fQ.MMTqHaROX69WEDrCdHK9DFToA49CeraVzQC4zGn08CrSz3GCiA7HabbFaZAZLeKtoK0Z_-OulPMoVgZhCW9R7g","status":true,"expire":1563300917916}
    
    • Gursewak Singh
      Gursewak Singh almost 5 years
      We need to know more about what your API is expecting. If the request in Postman is working, please share the exact request Postman is generating, by clicking code near the top right of PostMan, setting the format to cURL, and adding the output to your question
    • isaac cubas
      isaac cubas almost 5 years
      This? curl -X POST \ URLSample..orSomething \ -H 'Content-Type: application/json' \ -H 'Postman-Token: a3621ffc-f029-4973-b015-c7fea1c2b429' \ -H 'cache-control: no-cache' \ -d '{ "username" : "administrador", "password" : "admin2010" }'
  • isaac cubas
    isaac cubas almost 5 years
    Well, this is a topic of my work, and I indicated that it was with the post method, so I think that would not be the error, that you have to use another method and that it was equivalent to saying it