user11065582
user11065582

Reputation:

How to Http Post with Json Body on Flutter

I am trying to get data from API. I need to pass value from the body, in postman without a header: application/JSON data is not displayed.

final response = await http.post(
      "http://192.168.10.25:8080/Login/validateusername",
    body: {"username": "user@PYA"},
      headers: {'Content-Type': 'application/json'},
    );

Error Message:

E/flutter (28851): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (28851): Bad state: Cannot set the body fields of a Request with content-type "application/json".

enter image description here

Upvotes: 4

Views: 25129

Answers (6)

Dilhan Jayathilake
Dilhan Jayathilake

Reputation: 1890

Another simple way is as bellow

import 'package:http/http.dart' as http;

String body = json.encode({
    'foo': 'bar',
    'complex_foo' : {
        'name' : 'test'     
    }
});

http.Response response = await http.post(
    url: 'https://example.com',
    headers: {"Content-Type": "application/json"},
    body: body,
);

Upvotes: 5

wafL
wafL

Reputation: 655

I am doing almost the same. However, I tried to avoid doing back-end, like in your case. I just did a minimal php request so that I would not waste or patience learning what is needed to develop a user management controller.

However, I faced several limitations and problems that Flutter alone can't solve. After some denial, I gave a try. Lumen, a light version of the Laravel Framework, some tutorials and some past experience, I eventually realized that the API should carry most of the authentication, and not the application itself. I digressed.

In my case, the code of the fuction to a http post is:

Future<Post> createPost() async {
final url = "http://localhost:8000/api/login";
Map<String, String> body = {
  'user': user.text,
  'pass': pass.text,
};
await http.post(url, body: body);
print(body);

return http.;

}

I first convert it into a map. I prefer this method over parsing json, because down the line, if I need to add more variables, I just make the map bigger.

I just have a question: What does your http://192.168.10.25:8080/Login/validateusername look like? I think that there is no need to specify the type of information that your body parses.

Upvotes: 0

Adel Ben Hamadi
Adel Ben Hamadi

Reputation: 770

Simply encode body to json object when using content-type "application/json"

http.Response response = await http.post( uri , headers: headers, body: JsonEncoder().convert(body));

Upvotes: 6

Adonis Gonz&#225;lez
Adonis Gonz&#225;lez

Reputation: 2068

var json = jsonCodec.encode(data);
    print("json=$json");
    var url = "http:yourAPIrouter.com/etc";
    var response = await http.post(
      url,
      headers:{ "Accept": "application/json" } ,
      body: { "json": '$json'},
      encoding: Encoding.getByName("utf-8")
    );

and dont forget add the key "json" in postman

enter image description here

Upvotes: 0

Rahul Devanavar
Rahul Devanavar

Reputation: 4165

Add the content type application/json

Future<String> apiRequest(String url, Map jsonMap) async {
  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

Upvotes: 6

Pompidou
Pompidou

Reputation: 607

use the http dart package

var data = {username:"username",password:"password"};
 http.Response response = await http.post(
        "yourApiroute",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: {"username": data.phone, "password": data.password});

Upvotes: 3

Related Questions