我正在尝试连接 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 一起工作,这些是步骤:
- 将 IIS 更改为您的本地运行时环境(默认为项目名称)
- 删除
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/