Charanveer Singh
Charanveer Singh

Reputation: 31

body not sending using map in flutter

HttpClient client = new HttpClient();
    client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);

    String url ='https://dev.jobma.com:8090/v4/jobseeker/login';
    Map map = {
      "email":"[email protected]",
      "password":"123456"
    };
    print(map);
    HttpClientRequest request = await client.postUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/json');
    request.add(utf8.encode(json.encode(map)));
    HttpClientResponse response = await request.close();
    String reply = await response.transform(utf8.decoder).join();
    print(reply);

and response from server showing this

{"error": 1, "data": {}, "message": "Please add mandatory fields: email, password"}

Upvotes: 1

Views: 1217

Answers (2)

Bulky Brains
Bulky Brains

Reputation: 31

It is much easier if you can use http package available in dart pub.

import 'package:http/http.dart' as http;
String url = 'https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
  "email": "[email protected]",
  "password": "123456"
};

var response = await http.post(url, body: map);

print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

Upvotes: 2

J. S.
J. S.

Reputation: 9635

It seems that without the "content-length" headers, that server isn't accepting the request properly. This will make your code work:

HttpClient client = new HttpClient();

client.badCertificateCallback =
  ((X509Certificate cert, String host, int port) => true);

String url = 'https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
  "email": "[email protected]",
  "password": "123456"
};
print(map);

// Creating body here
List<int> body = utf8.encode(json.encode(map));

HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');

// Setting the content-length header here
request.headers.set('Content-Length', body.length.toString());

// Adding the body to the request
request.add(body);

HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);

Upvotes: 1

Related Questions