在使用Flutter编写手机app时,开发过程中想要通过调用本地的后台服务来获取数据,但是每次都会报错:
SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 38396
这里调用时的api请求路径:http:localhost:10086/auth
之前因为忙于开发,查了下资料都没有解决问题,时间紧,任务重,就直接将后台api部署到云环境,通过调用云函数来获取数据。但是这样做,每次修改api都得部署到云环境上,app才能正确获取数据,很麻烦,但是当时也没有其他的办法和时间,所以将就了。
现在开发阶段已经结束了,趁着有时间,再回过头来调查,经过测试,已完美解决该问题,能够通过调用本地后台api获取数据。深层次的原因还没调查到,待日后调查到根本原因后再记录,这里只记录一下解决方案。
1.首先,我们访问本地后台api时的http请求不能使用 http:localhost:10086/auth 这样的URL,或者 http:127.0.0.1:10086/auth 这样的也不行,需要将这里的 localhost 或 127.0.0.1 替换成 本机的真实 IPv4 地址,例如 192.166.1.12 (获取本机ip地址方式可以参考:Linux获取本机ip?或 Windows获取本机ip),替换后的请求地址就变成了? http:192.166.1.12:10086/auth
2.找到 android/app/src/main/AndroidManifest.xml 这个文件,如果没有就自己创建一个,然后添加如果内容:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my_app">
<application
android:label="my_app"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true"
>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
其中重要的是
<application android:label="ares_app_restaurant"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
</application>
<uses-permission android:name="android.permission.INTERNET" />
如果是IOS,需要将下面这段添加到 ios/Runner/info.plist文件中
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
再次编译运行,成功。
参考来源:Bad state: Insecure HTTP is not allowed by platform: [closed]
|