1

我有用于获取列表的 auth_key。

我尝试了很多次,但 auth_key 没有进入第二个屏幕,因为我无法从 Internet 获取数据我在 Postman 中使用 JSON 请求标头测试了 API,它似乎工作正常。

这是响应... { "error": false, "message": "success", "course_list": [ { "courseId": "19", "courseName": "Verbs-01-def-prctice", “价格”:“0”,“sub_type”:“1”,“sku_id”:“15464”,“courseIcon”:“”,“类型”:“0”,“付费”:假},

    **Now on my Flutter application I am trying to do the same thing:  
**
    
        
    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    import 'package:http/http.dart';
    
    class SecondScreen extends StatefulWidget {
      @override
      _SecondScreenState createState() => _SecondScreenState();
    }
    
    class _SecondScreenState extends State<SecondScreen> {
      String url = '';
      List data;
    
      @override
      void initState() {
        super.initState();
        this.getJsonData();//call method here
      }
    
      Future<http.Request> getJsonData() async {
        var response = await http
            .get(url, headers: {'auth_key': '7tJBAO3xwIF3UhfIwMYryL2Cqo1dpQ'});//this is my auth_key(token)
    
        print(response.body);
    
        setState(() {
          var convertDataToJson = json.decode(response.body);
          data = convertDataToJson['results'];
        });
      }
    
      @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]['courseName']),
                          padding: EdgeInsets.all(20.0),
                        ),
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        );
      }
    }

运行此应用程序后...

Xcode 构建完成。14.3s 安装和启动...正在将文件同步到设备 Samcom Tech 的 iPhone...flutter: {"error":true,"message":"Sorry, Auth key is not defined"} [在此处输入图像描述][1]

4

3 回答 3

0

通常,您需要在标题中使用“授权”而不是“auth_key”。请尝试一下。或者,请尝试以下示例:

Map<String, String> headers = {
  HttpHeaders.authorizationHeader: "7tJBAO3xwIF3UhfIwMYryL2Cqo1dpQ",
  HttpHeaders.contentTypeHeader: "application/json"
};
var response = await http
        .get(url, headers: headers);
于 2019-07-24T07:47:39.353 回答
0

如果你想有一个很棒的库来处理你的 http 请求,叫做 CHOPPER: https ://pub.dev/packages/chopper

您还可以在以下位置找到很棒的教程: https ://www.youtube.com/watch?v=zFXK5EsrUF0&t=1553s

这是一个代码示例:

// my_service.dart

import "dart:async";
import 'package:chopper/chopper.dart';

part "my_service.chopper.dart";

@ChopperApi(baseUrl: "/resources")
abstract class MyService extends ChopperService {
  static MyService create([ChopperClient client]) => _$MyService(client);

  @Get(url: "{id}")
  Future<Response> getResource(@Path() String id);

  @Get(headers: const {"foo": "bar"})
  Future<Response<Map>> getMapResource(@Query() String id);

  @Post(url: 'multi')
  @multipart
  Future<Response> postResources(
    @Part('1') Map a,
    @Part('2') Map b,
    @Part('3') String c,
  );

  @Post(url: 'file')
  @multipart
  Future<Response> postFile(
    @FileField('file') List<int> bytes,
  );
}
于 2019-07-24T08:30:10.707 回答
0

请尝试以下代码:

response = http.get(URL, headers: {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
        "auth_key': '7tJBAO3xwIF3UhfIwMYryL2Cqo1dpQ"
      }).then((http.Response response) {});
于 2019-07-24T08:40:00.513 回答