Flutter:错误:内部服务器错误,代码500

时间:2019-07-15 20:21:03

标签: android http post flutter postman

当使用flutter连接到端点时,它在到期时间变量旁边返回错误500,现在仅当我发送用户名和密码时才发生这种情况,事情是,使用PostMan使用相同的信息,结果是代码200和所有相应的变量。可能是什么问题?

基本上可以与Android Studio和邮递员结合使用

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
            ]),
      ),
    );

  }
}

使用星期二代码打印(response.body); 输出为:

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

使用邮递员周二的输出是:

{"access-token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBRE1JTklTVFJBRE9SIiwiZXhwIjoxNTYzMzAwOTE3fQ.MMTqHaROX69WEDrCdHK9DFToA49CeraVzQC4zGn08CrSz3GCiA7HabbFaZAZLeKtoK0Z_-OulPMoVgZhCW9R7g","status":true,"expire":1563300917916}

2 个答案:

答案 0 :(得分:0)

您确定请求方法是Post吗?如果不是,那可能是导致错误的原因。 签入:await http.post

答案 1 :(得分:0)

这是您在上面的评论中说的cURL请求,格式更好一些:

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" }'

正如您在Content-Type标头中所看到的,Postman(和cURL)告诉服务器在请求正文中期望JSON数据。您还可以看到正在发送JSON有效负载。

现在查看您的代码,我们可以开始理解为什么它不起作用。您没有在请求中设置内容类型标头,但更重要的是,您没有发送JSON。

这是您的请求正文:

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

这实际上是镖Map<String, dynamic>。从http文档中,这将被编码为表单数据,而不是JSON:

  

如果body是Map,则使用编码将其编码为表单字段。请求的内容类型将设置为“ application / x-www-form-urlencoded”;这不能被覆盖。

因此,要解决您的请求,我们应该设置Content-Type标头,然后自己进行JSON编码。最终看起来像这样:

// 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'},

);
相关问题