How to make HTTP POST request with url encoded body in flutter?

flutter http post request example
flutter http post json
http post flutter
flutter post request example
flutter http post example
flutter http post json body
flutter http post request with parameters
flutter http timeout

I'm trying to make an post request in flutter with content type as url encoded. When I write body : json.encode(data), it encodes to plain text.

If I write body: data I get the error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast

This is the data object

var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};

And my request

var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: match,
    encoding: Encoding.getByName("utf-8"));

You need to add three additional steps: First you need to convert the json map to a String (using json.encode) Then you need to Uri encode it if you want to send it as application/x-www-form-urlencoded. Lastly, you need to give the parameter that you are posting a name.

For example (note, this is using the dart:io HttpClient, but it's basically the same):

  Future<HttpClientResponse> foo() async {
    Map<String, dynamic> jsonMap = {
      'homeTeam': {'team': 'Team A'},
      'awayTeam': {'team': 'Team B'},
    };
    String jsonString = json.encode(jsonMap); // encode map to json
    String paramName = 'param'; // give the post param a name
    String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
    List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
    HttpClientRequest request =
        await _httpClient.post(_host, _port, '/a/b/c');
    // it's polite to send the body length to the server
    request.headers.set('Content-Length', bodyBytes.length.toString());
    // todo add other headers here
    request.add(bodyBytes);
    return await request.close();
  }

The above is for the dart:io version (which, of course, you can use in Flutter) If you would like to stick with the package:http version, then you need to tweak your Map a bit. body must be a Map<String, String>. You need to decide what you want as your POST parameters. Do you want two: homeTeam and awayTeam? or one, say, teamJson?

This code

  Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'homeTeam': json.encode(
      {'team': 'Team A'},
    ),
    'awayTeam': json.encode(
      {'team': 'Team B'},
    ),
  };

  Response r = await post(
    url,
    body: body,
  );

produces this on the wire

name=doodle&color=blue&homeTeam=%7B%22team%22%3A%22Team+A%22%7D&awayTeam=%7B%22team%22%3A%22Team+B%22%7D

alternatively, this

  Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'teamJson': json.encode({
      'homeTeam': {'team': 'Team A'},
      'awayTeam': {'team': 'Team B'},
    }),
  };

  Response r = await post(
    url,
    body: body,
  );

produces this on the wire

name=doodle&color=blue&teamJson=%7B%22homeTeam%22%3A%7B%22team%22%3A%22Team+A%22%7D%2C%22awayTeam%22%3A%7B%22team%22%3A%22Team+B%22%7D%7D

the package:http client takes care of: encoding the Uri.encodeQueryComponent, utf8 encoding (note that that's the default, so no need to specify it) and sending the length in the Content-Length header. You must still do the json encoding.

Post data as x-www-form-urlencoded worked on android but not on , Post data as x-www-form-urlencoded worked on android but not on ios #24211 toString()); final response = await http.post(url, //body: body, body: unreadable data on the server, there is nothing wrong with flutter Already have an account? Successfully merging a pull request may close this issue. Now replace /posts with /posts/1 in the url. Using /posts returns an array of JSON objects while /posts/1 returns a single JSON object, where 1 is the ID of the post you want to get. You can use dart:convert to convert the raw JSON string to objects. See Parsing Simple JSON in Flutter and Dart for help with that.

I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio is very easy to use, in your case you can:

Map<String, String> body = {
'name': 'doodle',
'color': 'blue',
'teamJson': {
  'homeTeam': {'team': 'Team A'},
  'awayTeam': {'team': 'Team B'},
  },
};

dio.post("/info",data:body, options: 
  new Options(contentType:ContentType.parse("application/x-www-form-urlencoded")))    

dio can encode the data automatically.

More details please refer to dio.

How to make HTTP requests in Flutter - The Startup, This answer tells how to make HTTP requests using the http package by the Response response = await post(url, headers: headers, body: json); // check the final encodedCredentials = stringToBase64.encode(credentials);Map<String,  2.Create Post Class. First, we’ll need to create a Post class that contains the data from our network request. It will also include a factory constructor that allows us to create a Post from json.

you need to use json.encode

example;

var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};
var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: json.encode(match),
    encoding: Encoding.getByName("utf-8"));

post function - http library, API docs for the post function from the http library, for the Dart programming get · head · patch · post · put · read · readBytes · Exceptions · ClientException dynamic url,; {Map<String, String> headers,; dynamic body,; Encoding encoding}. ) Sends an HTTP POST request with the given headers and body to the given URL,  This is a network util class that we can use it anywhere to perform http request in a Flutter Application. In the following class, we have created a method for GET and POST request. You can add other methods of http according to your requirement. In this file, we have created a field BASE_URL.

I came here just trying to make an HTTP POST request. Here is an example of how to do that:

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


makePostRequest() async {

  final uri = 'http://httpbin.org/post';
  final headers = {'Content-Type': 'application/json'};
  Map<String, dynamic> body = {'id': 21, 'name': 'bob'};
  String jsonBody = json.encode(body);
  final encoding = Encoding.getByName('utf-8');

  Response response = await post(
    uri,
    headers: headers,
    body: jsonBody,
    encoding: encoding,
  );

  int statusCode = response.statusCode;
  String responseBody = response.body;
}

postFormData method - HttpRequest class - dart:html , Makes a server POST request with the specified data encoded as form data. This method is similar to sending a FormData object with broader browser support but limited to String encodeQueryComponent and converted into an HTTP query string. Content-Type: application/x-www-form-urlencoded; charset​=UTF-8. Luckily, Dart and Flutter provide tools, such as the http package, for this type of work. This recipe uses the following steps: Add the http package. Make a network request using the http package. Convert the response into a custom Dart object. Fetch and display the data with Flutter.

How To Make A HTTP ~POST~ Request with JSON as The Body in , How To Make A HTTP ~POST~ Request with JSON as The Body in Dart or Flutter​. import 'package:http/http.dart' as http; Map data = { 'key1': 1, 'key2': "some text" } String body = json.encode(data); http.Response response = await http.post( url: '​https://example.com', headers: {"Content-Type": "application/json"}, body:  Doing an HTTP Post with headers and a body. How to make HTTP POST request with url encoded body in flutter? 23. HTTP POST with Json on Body - Flutter/Dart. 1.

How to handle the POST request body in Dart without using a , Learn how to deal with POST requests made to your server payload is application/x-www-form-urlencoded , which essentially describes data that Create a main.dart file and enter the snippet below: This bootstraps our server and responds with a form when a request is made to http://localhost:9000 . 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.

post( url, [body], [params] ), body, string / object, Request body; objects will be x-www-form-urlencoded . params (optional) Using http.post() to perform a user login at an E-commerce site:. I have a problem with the response from the request, where its suppose to have a body with json, but something went wrong and i think is with the json that i send on the body request, because it is a nested json object, and the value of the key is a json object. i would love to know how i can parse the json right and insert into body of the

Comments
  • If you don't care for a specific port, httpClient.postUrl also works!
  • Thank you for the answer. But it seems that this solution is only working for objects that are not embedded with other objects. Hence if I remove the homeTeam object and awayTeam object, it works fine.
  • according to documentation- [body] sets the body of the request. It can be a [String], a [List<int>] or a [Map<String, String>]. If it's a String, it's encoded using [encoding] and used as the body of the request. The content-type of the request will default to "text/plain".
  • So I have to set the content type to application/json if I want to send complex structures. url-encoded will only work for single level objects.
  • Looks promising. @wendu what are the benefits using this module?
  • If you are affiliated with the package, please disclose your affiliation in the post.
  • That encoding part really helped me.
  • In http/http.dart, it will not work if we encode the body using json.encode. Just pass the body as a map and it will be encoded as form fields using encoding.
  • This is what completed the example for me. I made a map but passing it as a parameter to http.post (in body) didn't make it. Encoding it, my PHP rest api could read it perfectly.