flutter - 如何使用标题调用http-get api?

标签 flutter dart httprequest httpresponse

现在,在我的Flutter应用程序中,我正在尝试执行相同的操作:

运行此应用程序后...

 {"error":true,"message":"Sorry, Auth key is not defined"} 

我的代码是:
class Post {
          String username;
          Post({this.username});// call post API

          factory Post.fromJson(Map<String, dynamic> json) {
            return Post(username: json['username']);
          }

          Map toMap() {
            var map = new Map<String, dynamic>();

            map["username"] = username;// post username
            return map;
          }
        }

        class MyApp extends StatelessWidget {
          final Future<Post> post;

          MyApp({Key key, this.post}) : super(key: key);

          // This widget is the root of your application.
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              home: HomeScreen(),
              debugShowCheckedModeBanner: false,
              theme: ThemeData(primarySwatch: Colors.blue),
            );
          }
        }

        class HomeScreen extends StatefulWidget {
          @override
          _HomeScreenState createState() => _HomeScreenState();
        }

        class _HomeScreenState extends State<HomeScreen> {
          static final url = "http://xxxx.xxxxx.xxxx/xxxxx/login";// login API

          TextEditingController _nameController = TextEditingController();

          @override
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: Text("Quiz App"),
              ),
              body: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "User Name",
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 30,
                          color: Colors.blueAccent),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: TextFormField(
                        controller: _nameController,
                        maxLines: 1,
                        decoration: InputDecoration(
                          hintText: "User Name",
                          labelText: "Name",
                          border: new OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(10.0),
                            ),
                            borderSide: new BorderSide(
                              color: Colors.blueAccent,
                              width: 2.0,
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      width: 150,
                      height: 50,
                      child: FlatButton(
                        shape: new RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(10.0)),
                        color: Colors.blue,
                        onPressed: () async {
                          Future<Post> createPost(String url, {Map body}) async {
                            return http
                                .post(url, body: body, headers: {"auth_key": "xxxxxxxxx"})
                                .then((http.Response response) {
                              if (response.body.contains("xxx")) {
                                print("false value :" +response.body.toString());
                              } else if (response.body.contains("Success")) {
                                print("true value :" + response.body.toString());

                                //checkIsLogin();

                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => SecondScreen()));
                              } else {
                                print("else value :" + response.body.toString());
                              }

                              return Post.fromJson(json.decode(response.body));
                            });
                          }

                          Post newPost = new Post(username: _nameController.text);
                          Post p = await createPost(url, body: newPost.toMap());
                          print(p.username);
                        },
                        child: Text(
                          "SUBMIT",
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 15,
                              color: Colors.white,
                              letterSpacing: 1),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            );
          }
        //save username with shared pref.
          @override
          void initState() {
            super.initState();
            checkIsLogin();
          }

          Future<Null> checkIsLogin() async {
            String _auth_key = "";
        //save key in shared pref
            SharedPreferences prefs = await SharedPreferences.getInstance();
            _auth_key = prefs.getString("auth_key");

            if (_auth_key != "" && _auth_key != null) {
            } else {
              Navigator.pushReplacement(
                  context, MaterialPageRoute(builder: (context) => SecondScreen()));
            }
          }
        }

        //this is secondscreen where call get api
        class SecondScreen extends StatefulWidget {


          @override
          _SecondScreenState createState() => _SecondScreenState();
        }

        class _SecondScreenState extends State<SecondScreen> {
          static final url = "http://xxxx.xxxxx.xxxxxxx/xxxxxx/allCourse/";// course lisr API
          List data;// save in list

          @override
          void initState() {
            super.initState();
            this.getJsonData();
          }

            Future<http.Request> getJsonData() async {
            Response response = await http
                .get(url, headers: {'Header': 'xxxxxxx'});


            print(response.body);

            setState(() {
              var convertDataToJson = json.decode(response.body);
              data = convertDataToJson["course_list"];
            });
          }

        //save data in list
          @override
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: Text("Courses"),
              ),
              body: new ListView.builder(
                itemCount: data == null ? 0 : data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Center(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: <Widget>[
                          Card(
                            child: Container(
                              child: Text(data[index]['xxxx']),
                              padding: EdgeInsets.all(20.0),
                            ),
                          )
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          }
        }`

我有auth_key用于获取列表。

我在Postman中使用JSON请求 header 测试了API,看来工作正常。

这是回应...
{ "error": false, "message": "success", "course_list": [ { "courseId": "19", "courseName": "Verbs-01-def-prctice", "price": "0", "sub_type": "1", "sku_id": "15464", "courseIcon": "", "type": "0", "paid": false },

最佳答案

尝试改变

 Response response = await http.get(url, headers: {'Header': 'xxxxxxx'});


Response response = await http.get(Uri.encodeFull(url), headers:{"auth_key": "xxxxxxxxx"}) 
//the term "auth_key" used here should be the correct name the server 
//is expecting for the authentication key. EDIT: In your Postman screen shot
// your have the key as "Header"

https://flutter.dev/docs/cookbook/networking/authenticated-requests

关于flutter - 如何使用标题调用http-get api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195294/

相关文章:

firebase - 在 org.gradle.api.Project 类型的项目 ':app' 上找不到参数 [] 的方法 Properties()

arrays - 如何从渲染列表中访问对象键?

git - 我们应该在 Flutter 项目中将 Podfile.lock 添加到 .gitignore 吗?

flutter - flutter :BoxConstraints强制无限高

flutter - 当 child 等待 parent 的设置状态完成时,如何在两个有状态小部件之间使用 FutureBuilder?

user-interface - 如何使DropdownButtonFormField占用尽可能小的空间?

java - 在http请求字符串url中添加文本

java - Vert.x Http 请求未将参数分配为配置

php - 将数组从 PHP 发送到 GWT 的问题

unit-testing - Flutter - 小部件中的测试抽屉如何测试?