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

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

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

基本上将 flutter 与 Android Studio 和 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
            ]),
      ),
    );

  }
}

使用 tue 代码 print(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"}

使用邮递员 tue 输出是:

{"access-token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJBRE1JTklTVFJBRE9SIiwiZXhwIjoxNTYzMzAwOTE3fQ.MMTqHaROX69WEDrCdHK9DFToA49CeraVzQC4zGn08CrSz3GCiA7HabbFaZAZLeKtoK0Z_-OulPMoVgZhCW9R7g","status":true,"expire":1563300917916}
android http post flutter postman
3个回答
4
投票

这是您在上面的评论中所说的 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,则使用编码将其编码为表单字段。请求的content-type将被设置为“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'},

);

0
投票

您确定请求方法是Post吗?如果不是,可能就是错误原因。 检查一下:

await http.post


0
投票

我也有同样的问题,请问解决了吗?谢谢

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