如何在Flutter中的HTTP发布请求中传递标头?

时间:2019-10-14 13:24:31

标签: flutter

调试我的应用程序时,出现“ 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

传递标题

5 个答案:

答案 0 :(得分:0)

以下是在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)

答案 1 :(得分:0)

尝试这样

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

答案 2 :(得分:0)

您只想在帖子中添加标题。所有标题均应为Map格式

 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));
  });
}

答案 3 :(得分:0)

尝试一下


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

答案 4 :(得分:0)

这是在 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();
            },
          ),
        ),
      ),
    );
  }
}