Ikhsannul Hijri
Ikhsannul Hijri

Reputation: 366

Server API not accept JSON edcoded data Flutter

Edit: After hours of work, i might because when i send "content-type": "application/json", it send "application/json; charset=utf-8" to server. How to remove ; charset=utf-8 from header?

Edit2: The problem is because flutter send charset=utf-8 in Content-type. I fix by contact my backend developer to allow "application/json; charset=utf-8" in Content-type header

I send post request to server, return error

{"error":"true","code":"30","message":" Data must JSON"}

This is my code:

Future<void> _getToken() async {
final url =
    Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
final Map<String, String> data = {
  "username": "xxxx",
  "password": "xxxx"
};
try {
  final response = await http.post(url,
      headers: {
        "Content-Type": "application/json",
        "accept": "application/json",
      },
      body: jsonEncode(data));
  print(response.body);
  final responseData = jsonDecode(response.body);
  _token = responseData["message"];
} catch (error) {
  throw error;
 }
}

Is there something wrong in my code? 🤔

The API work on Postman, ThunderClient VS Code, and React Native

enter image description here

Thanks for your help

Upvotes: 0

Views: 532

Answers (3)

Create model like this:

import 'dart:convert';

LoginData loginDataFromJson(String str) => LoginData.fromJson(json.decode(str));

String loginDataToJson(LoginData data) => json.encode(data.toJson());

class LoginData {
  LoginData({
    required this.username,
    required this.password,
  });

  final String username;
  final String password;

  factory LoginData.fromJson(Map<String, dynamic> json) => LoginData(
        username: json["username"],
        password: json["password"],
      );

  Map<String, dynamic> toJson() => {
        "username": username,
        "password": password,
      };

  @override
  String toString() {
    return '$runtimeType($username, $password)';
  }

  @override
  bool operator ==(Object other) {
    if (other is LoginData) {
      return username == other.username && password == other.username;
    }
    return false;
  }

  @override
  int get hashCode => hash2(username, password);
}

And now you can write your code like this:

Future<void> _getToken() async {
final url =
    Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
final LoginData data = LoginData(
  username: "xxxx",
  password: "xxxx"
);
try {
  final response = await http.post(url,
      headers: {
        "Content-Type": "application/json",
        "accept": "application/json",
      },
      body: data.toJson());
  print(response.body);
  final responseData = jsonDecode(response.body);
  _token = responseData["message"];
} catch (error) {
  throw error;
 }
}

Upvotes: 1

JuniorBOMB
JuniorBOMB

Reputation: 399

Try encode your data using convert

import 'dart:convert' as convert;

//...

const JsonEncoder encoder = JsonEncoder();
final response = await http.post(url,
    headers: {
        "Content-Type": "application/json",
        "accept": "application/json",
    },
    body: encoder.convert(data)
);

Hope this will help

Upvotes: 0

Unknown Developer
Unknown Developer

Reputation: 167

The headers field in the http.post method has to be changed to have Content-Type equal to application/json and accept equal to application/json.

Future<void> _getToken() async {
      final url =
          Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
      final Map<String, String> data = {
        "username": "xxxx",
        "password": "xxxx"
      };
      try {
        final response = await http.post(url,
            headers: {
              "Content-Type": "application/json",
              "accept": "application/json",
            },
            body: jsonEncode(data));
        print(response.body);
        final responseData = jsonDecode(response.body);
        _token = responseData["message"];
      } catch (error) {
        throw error;
      }
    }

Upvotes: 0

Related Questions