android - Bad Request 400 从 Flutter 请求 ASP.Net Core 3.0

标签 android asp.net-core flutter

我正在尝试连接 Flutter 的 HttpClient 以从我在 ASP.Net Core 3.0 上运行的本地服务器获取数据。问题是我每次尝试都会收到错误 400(错误请求)。

这是 flutter 代码:

    String token = await SharedPreferencesService.getStringFromSF('idToken');
    var client = new HttpClient();
    client.badCertificateCallback =
        (X509Certificate cert, String host, int port) => true;

    HttpClientRequest request =
        await client.getUrl(Uri.parse('https://10.0.2.2:44383/weatherforcast'));
    request.headers.add('idToken', token);

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

asp.net core 3.0 端点:

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public User Get()
        {
            return new User { UserId = 1332, Username = "Michal" };
        }
    }

错误

<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>

我可以确认我在浏览器和 postman 上都获得了数据。 感谢您的帮助。

最佳答案

好的,我通过逐步调试解决了这个问题。

Android 似乎不喜欢自签名证书,因此我最终无法真正将其设置为使用 HTTPS。

不过我所做的是让它与单一 HTTP 一起工作,这些是步骤:

  1. 将 IIS 更改为您的本地运行时环境(默认为项目名称)
  2. 删除app.UseHttpsRedirection();在服务端配置方法

我们现在启用了对我们服务器的 HTTP 请求。接下来是通过我们的本地运行时环境运行服务器(我们可以在 VS 中的“调试”按钮中进行更改)。

现在,我们应该能够在 Android Emulator 的浏览器中使用 http 请求访问 api,例如http://localhost:5000/weatherforcast . 请记住,ASP.NET Core 3.0 默认在端口 5001 上提供 HTTPS,在 5000 上提供 HTTP。

接下来,Android 为服务器运行的本地机器的 IP 使用别名,所以不用写 localhost:<port>我们必须写10.0.2.2:<port>

最后,我简化了客户端中的 api 调用,如下所示:

static Future<Profile> getUserProfile() async {
    String url = 'http://10.0.2.2:5000/weatherforecast';
    final reply = await http.get('$url');
    var responseJson = json.decode(reply.body);
    return Profile.fromJson(responseJson);
  }

关于android - Bad Request 400 从 Flutter 请求 ASP.Net Core 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58367151/

相关文章:

angular - DOM 异常 : Failed to read the 'localStorage' property from 'Window' : In Chrome Incognito mode and running in Iframe

testing - 使用 flutter 驱动程序中的系统后退按钮

在 iOS 模拟器中收到 Firebase FCM 通知,但在 Flutter 应用程序的真实 iOS 设备上收到 GCM(?)

java - 如何在从 Web 服务器接收图标 URL 时将图标添加到自定义 ListView 中

java - 如何用图像中的蓝色半透明圆替换我的 Android 应用 Google map 半径圆?

java - 我的应用违反了站点行为 : Navigation and i don't knew why?

android - 在 Android 中调用 .NET 网络服务

asp.net - 过滤掉 ASP.NET Core API 中的属性

asp.net-core - "TransformWebConfig"任务意外失败 - System.Exception : The acceptable value for AspNetCoreModuleHostingModel property is either

android-studio - 如何在 flutter 中编写条件语句?