Запрос почтового токена с флаттером: недействительный - PullRequest
0 голосов
/ 09 апреля 2020

Я делаю запрос к веб-API ASP. Net для получения токена. Я могу сделать это успешно с пакетом HTTP dart следующим образом:

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;

Нет проблем с почтальоном:

enter image description here

enter image description here

enter image description here

Теперь я хочу сделать то же самое с базовым классом dart: io в качестве сервера тестирования имеет самозаверяющий сертификат, который, как я обнаружил, для HTTP-пакета не имеет обхода (может быть, это неправильно), но я не могу понять, в чем причина ошибки, так как при отладке сервера запросы никогда не попадают в следующую строку 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 всегда:

"{"error":"unsupported_grant_type"}"

Поэтому я предполагаю, что моя кодировка или структура неверны, но со всеми возможностями, которые я пробовал, ничего не работает, любая помощь будет оценена .

1 Ответ

0 голосов
/ 09 апреля 2020

Я сделал то же самое, но в моем случае я запрашиваю soap веб-сервис, нижеприведенный код сделает работу за меня, я надеюсь, что это будет для вас

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');
    }
  }
...