1

I'm doing a post request to an ASP.Net Web API to acquire a token. I am able to do this successfully with the dart HTTP package as follow:

Uri address = Uri.parse('https://myaddress:myport/token');

var response = await http.post(
    address,
    body: {
      'username': 'MyUsername',
      'password': 'MyPassword',
      'grant_type': 'password'
    },
).timeout(Duration(seconds: 20));

return response.body;

No problem with Postman either:

enter image description here

enter image description here

enter image description here

Now I want to do the same with the base dart:io class, as the testing server has a self signed certificate which I found the HTTP package has no bypass for (might be wrong), but for the life of me I cannot figure out where I am going wrong as when I debug the server the requests never get hit with the following code:

Uri address = Uri.parse('https://myaddress:myport/token');

HttpClient httpClient = HttpClient();
httpClient.connectionTimeout = Duration(seconds: 20);
httpClient.badCertificateCallback = ((X509Certificate cert, String host, int port) => true); // Allow self signed certificates

HttpClientRequest request = await httpClient.postUrl(address);

final Map<String, String> payLoad = {
    'username': 'MyUsername',
    'password': 'MyPassword',
    'grant_type': 'password'
};

request.headers.contentType = new ContentType("application", "x-www-form-urlencoded", charset: "utf-8");
request.add(utf8.encode(json.encode(payLoad)));
// request.write(payLoad);

HttpClientResponse response = await request.close();
String responseBody = await response.transform(utf8.decoder).join();
httpClient.close();

responseBody is always:

"{"error":"unsupported_grant_type"}"

So I assume my encoding or structure is wrong, but with all possibilities I have tried, nothing works, any help would be appreciated.

Elmer
  • 384
  • 5
  • 19
  • I am not sure, but looks like "x-www-form-urlencoded" part is not what server expects. Try new ContentType("application", "json", charset: "utf-8") instead. – Alex Radzishevsky Apr 09 '20 at 12:31
  • @AlexRadzishevsky List of things I have tried was to long so I didn't post that, started of with "json", same error. – Elmer Apr 09 '20 at 12:33

1 Answers1

0

i did the same but in my case i am requesting a soap web service, the bellow code do the job for me i hope it will for you

Future<XmlDocument> sendSoapRequest(String dataRequest) async {

    final startTime = Stopwatch()..start();
    _attemptsRequest = 0;
    bool successful = false;
    String dataResponse;
    try {
      Uri uri = Uri.parse('https://address:port/ADService');
      var httpClient = HttpClient();
      httpClient.connectionTimeout = Duration(milliseconds: 5000);
      httpClient.idleTimeout = Duration(milliseconds: 5000);
      httpClient.badCertificateCallback = ((X509Certificate cert, String host, int port) => true); // Allow self signed certificates

      await httpClient
          .openUrl('POST', uri)
          .then((HttpClientRequest request) async {
        request.headers.contentType =
            new ContentType('application', 'text/xml', charset: 'UTF-8');
        _attemptsRequest++;
        request.write(dataRequest);

        await request.close().then((HttpClientResponse response) async {
       // var data =  await response.transform(utf8.decoder).join();
       // i didn't use this method cause it disorganize the response when there is high level of data, -i get binary data from the server-
          var data = await utf8.decoder.bind(response).toList();
          dataResponse = data.join();
          successful = true;
          httpClient.close();
        });
        _timeRequest = startTime.elapsed.inMilliseconds;
      });
    } catch (e) {
      if (_attemptsRequest >= getAttempts) {
        _timeRequest = startTime.elapsed.inMilliseconds;
        if (e is SocketException)
          throw Exception('Timeout exception, operation has expired: $e');
        throw Exception('Error sending request: $e');
      } else {
        sleep(const Duration(milliseconds: 500));
      }
    }

    try {
      if (successful) {
        XmlDocument doc;
        doc = parse(dataResponse);
        return doc;
      } else {
        return null;
      }
    } catch (e) {
      throw Exception('Error converting response to Document: $e');
    }
  }
Mohamed Dernoun
  • 776
  • 5
  • 13