2019-11-08
How to pass headers in the HTTP post request in Flutter?
stackoverflow
Question

I am getting "415 error unsupported media type" when i debug my application. I got to know that i am missing to pass the headers in the post query.

i have used map to pass the data, please help me on how to pass the headers.

Or please provide me a example for Signup/Register in Flutter using JSON

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

Please let me know how to pass the headers in this program for the http.post

Answer
1

Here is the example to pass headers in http request

Future<dynamic> get(String url) async {
    LogUtils.d("====URL GET Call:   $url");
    String token = PreferenceUtils.getString(AppConstants.LOGGED_IN);

    // ignore: unrelated_type_equality_checks
    var isConnected = await isInternetConnected();
    if (isConnected != true) {
      return Future.error(ApiException(Strings.internetNotConnected));
    }
    //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);
    });
  }

And For post

http.post(url,
            body: json.encode(body),
            headers: { 'Content-type': 'application/json',
              'Accept': 'application/json',
              "Authorization": "Some token"},
            encoding: encoding)
How to pass headers in the HTTP post request in Flutter?
See more ...