【问题标题】:Flutter - HttpClient works on apps, but not browser. .NET Core 3.1 WebAPI + Flutter2Flutter - HttpClient 适用于应用程序,但不适用于浏览器。 .NET Core 3.1 Web API + Flutter 2
【发布时间】:2021-05-06 14:57:53
【问题描述】:

我有一个非常简单的 WebAPI,它只是 .NET Core 3.1 的默认设置。我正在使用使用 .NET Core 自签名的证书。当我为使用 Flutter 2 构建的 macOS 发出网络请求时,一切正常。但是,如果我在 Chrome 中调试,它就不起作用。这是我正在使用的 Flutter 2 代码:

Future<int> getElements() async {
    print("getting weatherforecast");
    HttpClient client = new HttpClient();
    client
        .getUrl(Uri.parse("https://localhost:5001/weatherforecast"))
        .then((HttpClientRequest request) {
      // Optionally set up headers...
      // Optionally write to the request object...
      // Then call close.
      return request.close();
    }).then((HttpClientResponse response) {
      // Process the response.
      print(response.toString());
    });
    return 1;
  }

API:

[HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }

我尝试添加打印消息,但它似乎没有在 httpclient 中执行任何操作。我在调试工具中也没有看到来自浏览器的网络流量来发送请求。有什么想法吗?

【问题讨论】:

    标签: c# flutter


    【解决方案1】:

    我想通了,我必须添加一个不同的库,因为 HttpClient 不执行浏览器请求,所以我通过以下方式导入了 http_client:

    flutter pub add http_client
    

    然后将我的请求和导入更改为:

    import 'package:http_client/browser.dart' as http;
    ...
    Future<int> getElements() async {
        print("getting weatherforecast");
    
        http.BrowserClient client = new http.BrowserClient();
        var rs = await client
            .send(http.Request('GET', "https://localhost:5001/weatherforecast"));
        final textContent = await rs.readAsString();
        print(textContent);
        return 1;
      }
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 2012-10-09
      相关资源
      最近更新 更多