1

I am making post API call function with content type of application/x-www-form-urlencoded. I am unable to pass parameter in the post method. Below is the related function:

Future<ServerResponse> postAPICall(String apiName, Map<String, dynamic> params) async {
    var url = Webservices.baseUrl + version + apiName;
    var postUri = Uri.parse(url);

    var completer = Completer<ServerResponse>();
    HttpClient client = new HttpClient();
    client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
    HttpClientRequest request = await client.postUrl(postUri);
    request.headers.set("content-type", "application/x-www-form-urlencoded");
    request.headers.set("Authorization", Constant.authUser?.authToken == null
         ? ""
         : Constant.authUser.authToken);


    String jsonString = json.encode(params);
    String paramName = 'param';
    String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
    List<int> bodyBytes = utf8.encode(formBody);
    request.add(bodyBytes);
    HttpClientResponse response = await request.close();
    String data = await response.transform(utf8.decoder).join();
    var jsValue = json.decode(data);
    var serverResponseObj = ServerResponse.withJson(jsValue);
   completer.complete(serverResponseObj);
   return completer.future;
}
Nae
  • 14,209
  • 7
  • 52
  • 79
Sagar
  • 585
  • 1
  • 9
  • 28
  • Is there an error thrown? According to [here](https://api.flutter.dev/flutter/dart-io/HttpClientRequest-class.html) there's no `add` method defined over request. – Nae May 22 '20 at 10:37
  • @Nae i have read while googling so i applied the solution.so please if you have any idea then tell me – Sagar May 22 '20 at 10:48

2 Answers2

1

I'd use http library:

import 'dart:io';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FloatingActionButton(
        onPressed: () async {
          var response = await http.post(
            "https://postman-echo.com/post",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            body: "foo1=bar1&foo2=bar2",
          );
          assert(response.statusCode == HttpStatus.ok);
        },
      ),
    );
  }
}
Nae
  • 14,209
  • 7
  • 52
  • 79
  • due to certification error i have to user httpclient and thanks for you help but i have found the solution using both class and plugin – Sagar May 23 '20 at 10:53
  • only thing that worked for me is sending the body as a string, like in this answer – Csaba Mihaly Jul 07 '23 at 20:06
0

postUrl method accepts a Uri object, if you look into the API documentation of Uri you'll find out that Uri accepts query or queryParameters. So you can do it like this:

client.postUrl(Uri.http('example.com', '/foo', {'username': 'john'}))

// or use Uri.https if server use https
client.postUrl(Uri.https('example.com', '/foo', {'username': 'john'})) 
linxie
  • 1,849
  • 15
  • 20