【问题标题】:How to pass headers in the HTTP post request in Flutter?如何在 Flutter 中的 HTTP 发布请求中传递标头?
【发布时间】:2020-02-11 03:19:22
【问题描述】:

我在调试我的应用程序时收到“415 错误不支持的媒体类型”。 我知道我错过了在帖子查询中传递标题。

我已经使用map来传递数据,请帮助我如何传递标题。

或者请提供一个使用 JSON 在 Flutter 中注册/注册的示例

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Post {
  final String userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

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

  Map toMap() {
    var map = new Map<String, dynamic>();
    map["userId"] = userId;
    map["title"] = title;
    map["body"] = body;

    return map;
  }
}

Future<Post> createPost(String url, {Map body}) async {
  return http.post(url, body: body).then((http.Response response) {
    final int statusCode = response.statusCode;

    if (statusCode < 200 || statusCode > 400 || json == null) {
      throw new Exception("Error while fetching data");
    }
    return Post.fromJson(json.decode(response.body));
  });
}

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

  MyApp({Key key, this.post}) : super(key: key);
  static final CREATE_POST_URL = 'https://jsonplaceholder.typicode.com/posts';
  TextEditingController titleControler = new TextEditingController();
  TextEditingController bodyControler = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: "WEB SERVICE",
      theme: ThemeData(
        primaryColor: Colors.deepOrange,
      ),
      home: Scaffold(
          appBar: AppBar(
            title: Text('Create Post'),
          ),
          body: new Container(
            margin: const EdgeInsets.only(left: 8.0, right: 8.0),
            child: new Column(
              children: <Widget>[
                new TextField(
                  controller: titleControler,
                  decoration: InputDecoration(
                      hintText: "title....", labelText: 'Post Title'),
                ),
                new TextField(
                  controller: bodyControler,
                  decoration: InputDecoration(
                      hintText: "body....", labelText: 'Post Body'),
                ),
                new RaisedButton(
                  onPressed: () async {
                    Post newPost = new Post(
                        userId: "123", id: 0, title: titleControler.text, body: bodyControler.text);
                    Post p = await createPost(CREATE_POST_URL,
                        body: newPost.toMap());
                    print(p.title);
                  },
                  child: const Text("Create"),
                )
              ],
            ),
          )),
    );
  }
}

void main() => runApp(MyApp());

请告诉我如何在这个程序中为 http.post 传递标头

【问题讨论】:

    标签: flutter


    【解决方案1】:

    这是在http请求中传递标头的示例

    Future<dynamic> get(String url) async {
        //Pass headers below 
        return http.get(url, headers: {"Authorization": "Some token"}).then(
            (http.Response response) {
          final int statusCode = response.statusCode;
          LogUtils.d("====response ${response.body.toString()}");
    
          if (statusCode < 200 || statusCode >= 400 || json == null) {
            throw new ApiException(jsonDecode(response.body)["message"]);
          }
          return _decoder.convert(response.body);
        });
      }
    

    然后发帖

    http.post(url,
                body: json.encode(body),
                headers: { 'Content-type': 'application/json',
                  'Accept': 'application/json',
                  "Authorization": "Some token"},
                encoding: encoding)
    

    【讨论】:

    • 谢谢,我不得不删除 "Authorization": "Bearer $token"},encoding: encoding 并且成功了
    • 能否解释一下目的:" "Authorization": "Bearer $token"}, encoding: encoding"
    • @UnIUnited-Tech "Authorization" 是关键,"Bearer $token" 是用于 api 身份验证的自定义标头值的值,如果您的 api 没有此标头,则可以将其删除
    【解决方案2】:

    这样试试

    http.post(
          url,
          body: body,
          headers: {HttpHeaders.authorizationHeader: "Bearer " + token},
        ).then((http.Response response) {
    });
    

    【讨论】:

      【解决方案3】:

      您只想在通话后添加标题。所有标题应为地图格式

       Future<Post> createPost(String url, {Map body}) async {
        return http.post(url, body: body,headers: {"Authorization": "Bearer"}).then((http.Response response) {
          final int statusCode = response.statusCode;
      
          if (statusCode < 200 || statusCode > 400 || json == null) {
            throw new Exception("Error while fetching data");
          }
          return Post.fromJson(json.decode(response.body));
        });
      }
      

      【讨论】:

      • 我的头文件是application/json,我使用了上面的代码。但得到以下错误:
      • ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理异常:异常:获取数据时出错
      • 你应该在标题中使用 'Content-type': 'application/json'
      【解决方案4】:

      试试这个

      
            return http.post(url,
                             body: jsonEncode(body),
                             headers: { 'Content-type': 'application/json'}
                            ).then((http.Response response) {
              final int statusCode = response.statusCode;
                           }
                      }
      

      【讨论】:

        【解决方案5】:

        这是在 http get 请求中传递标头的完整示例。

        在 punspec.yaml 中添加 http 依赖

        依赖: http: ^0.13.3, 最新:https://pub.dev/packages/http/install

        在此示例中,我在控制台中打印响应值。 之后我们可以将响应数据存储到列表中。

        import 'dart:async';
        import 'dart:convert';
        
        import 'package:flutter/material.dart';
        import 'package:http/http.dart' as http;
        
        Future<Album> fetchAlbum() async {
          final response =
              await http.get(Uri.parse('Enter your url(link)'),headers: {"Enter your key here":"Enter your Header Value here"});
              print("test in fetchAlbum()=> ${response.body}");
          if (response.statusCode == 200) {
            // If the server did return a 200 OK response,
            // then parse the JSON.
            return Album.fromJson(jsonDecode(response.body));
          } else {
            // If the server did not return a 200 OK response,
            // then throw an exception.
            throw Exception('Failed to load album');
          }
          //print('Test Func()');
        }
        
        class Album {
          final int userId;
          final int id;
          final String title;
        
          Album({
            required this.userId,
            required this.id,
            required this.title,
          });
        
          factory Album.fromJson(Map<String, dynamic> json) {
            return Album(
              userId: json['userId'],
              id: json['id'],
              title: json['title'],
            );
          }
        }
        
        void main() => runApp(MyApp());
        
        class MyApp extends StatefulWidget {
          MyApp({Key? key}) : super(key: key);
        
          @override
          _MyAppState createState() => _MyAppState();
        }
        
        class _MyAppState extends State<MyApp> {
          late Future<Album> futureAlbum;
        
          @override
          void initState() {
            super.initState();
            futureAlbum = fetchAlbum();
            print('initState()');
            print('test $fetchAlbum()');
            print('data ${futureAlbum}');
          }
        
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              title: 'Fetch Data Example',
              theme: ThemeData(
                primarySwatch: Colors.blue,
              ),
              home: Scaffold(
                appBar: AppBar(
                  title: Text('Fetch Data Example'),
                ),
                body: Center(
                  child: FutureBuilder<Album>(
                    future: futureAlbum,
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return Text(snapshot.data!.title);
                      } else if (snapshot.hasError) {
                        return Text("${snapshot.error}");
                      }
        
                      // By default, show a loading spinner.
                      return CircularProgressIndicator();
                    },
                  ),
                ),
              ),
            );
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-05-21
          • 2021-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-11
          • 1970-01-01
          相关资源
          最近更新 更多