Dart http POST Missing JSON Body

  Kiến thức lập trình

I’m trying to implement the most basic HTTP POST request to send a JSON object to an API.

Consider the example code below:

final http.Response response = await http.post(
    Uri.parse('http://localhost:8080/api/login'),
    body: jsonEncode({'username': 'testuser', 'password': 'testpass'}),
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json'
    }
);

When the above code is executed, my server receives the following request content from its socket connection:

POST /api/login HTTP/1.1
user-agent: Dart/3.4 (dart:io)
content-type: application/json; charset=utf-8
accept: application/json
accept-encoding: gzip
content-length: 45
host: localhost:8080


As you can see, the request that Dart sent is incorrect, because it is missing the 45 bytes of body content.

What am I missing? I’ve checked other similar questions and ruled out:

  • Adding/removing the content-type header (including case-sensitivity)
  • Supplying the body as a Map<String, dynamic> instead of a JSON String.
  • Using a http.Request instead of http.post.

If it’s of any importance, I’m currently developing on an AMD x86-64 Linux Mint pc, building and running my app as a Linux desktop application.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT