将Android应用程序连接到本地Laravel数据库[重复]

Posted

技术标签:

【中文标题】将Android应用程序连接到本地Laravel数据库[重复]【英文标题】:Connect Android app to local Laravel database [duplicate] 【发布时间】:2021-09-12 11:40:16 【问题描述】:

首先我想说的是,我一直在很多地方寻找答案,但我似乎找不到任何适合我的答案。最后,我将列出我已经尝试过的所有选项。我是 android 新手,这让我抓狂。

我要做的是向我的 Mac 上运行的本地 Laravel 数据库提交一个简单的 GET 请求。我正在尝试从模拟器上的 Android 应用程序调用此请求。 我的 Laravel 服务器在 127.0.0.1:8000 上运行并且它已打开。在 .env 文件中它声明 DB_PORT=3306,但是在请求中更改端口时并不重要。

我在 Android 中所做的事情:

String url = "http://127.0.0.1:8000/api/recipes"; // More on the IP at the end
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() 
        @Override
        public void onResponse(String response) 
            Log.d("heeftGewerkt", response.substring(30));
            errorMessage = "Succesful register";
        
    , new Response.ErrorListener() 
        @Override
        public void onErrorResponse(VolleyError error) 
            Log.d("heeftNietGewerkt", error.getMessage());
            errorMessage = "Unsuccesful register";
        
    );

我的 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a1114049_1090780_iiatimd_app">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:usesCleartextTraffic="true"
    android:theme="@style/Theme.1114049_1090780_iiatimd_app">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>

我了解当向 127.0.0.1 发送请求时,它可能会在 android 设备上寻找服务器,但显然无法找到。所以我尝试将 127.0.0.1:8000 替换为 localhost:8000、local-ip:8000 和 public-ip:8000。这些似乎都不起作用。

当我使用 Postman (http://127.0.0.1:8000/api/recipes) 向 Laravel 服务器发出请求时,它可以正常工作,并且我会在我的数据库中获取所有食谱。谁能帮我解决这个问题?

编辑: 我得到的错误是“无法连接到 /127.0.0.1:8000”。看看这可能是因为我没有在任何地方传递任何数据库凭据,但我也不确定是否应该。

【问题讨论】:

【参考方案1】:

使用10.0.2.2而不是localhost/127.0.0.1来访问你的实际机器

当在模拟器中时,本地主机指的是模拟器本身。但是模拟器支持转发到 ip 地址 10.0.2.2 上的主机

所以你的数据库服务器地址是

10.0.2.2:8000

【讨论】:

以上是关于将Android应用程序连接到本地Laravel数据库[重复]的主要内容,如果未能解决你的问题,请参考以下文章

使用 XAMPP 将 android 连接到本地服务器

将android设备连接到本地服务器xampp

Laravel 连接到 sql server

使用 Nodejs Restful API 将 android 应用程序连接到本地 mongoDB 数据库并将数据存储在 Mongodb 中(通过 WiFi)

Laravel Docker 容器未连接到本地 mysql

本地 Laravel 环境未连接到 AWS RDS 数据库