【问题标题】:Token Post Request With Flutter dart:io InvalidFlutter dart:io 的令牌发布请求无效
【发布时间】:2020-07-22 01:43:01
【问题描述】:

我正在向 ASP.Net Web API 发出发布请求以获取令牌。我可以使用 dart HTTP 包成功地做到这一点,如下所示:

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;

Postman 也没有问题:

现在我想对基础 dart:io 类做同样的事情,因为测试服务器有一个自签名证书,我发现 HTTP 包没有绕过它(可能是错误的),但对于我的一生,我无法弄清楚我哪里出错了,因为当我调试服务器时,请求永远不会被以下代码击中:

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"}"

所以我认为我的编码或结构是错误的,但我尝试了所有可能的方法,但没有任何效果,任何帮助将不胜感激。

【问题讨论】:

  • 我不确定,但看起来“x-www-form-urlencoded”部分不是服务器所期望的。试试 new ContentType("application", "json", charset: "utf-8") 。
  • @AlexRadzishevsky 我尝试过的事情清单太长了,所以我没有发布,从“json”开始,同样的错误。

标签: http flutter post dart dart-io


【解决方案1】:

我也这样做了,但在我的情况下,我请求的是一个肥皂网络服务,下面的代码为我完成了这项工作,我希望它对你有用

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

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2019-10-02
    • 2016-08-21
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多