首页 > 解决方案 > Android 应用程序(在模拟器中)不通过 h​​ttp 连接到本地 rest API

问题描述

Android avd 模拟器到 docker 中的本地 api。我可以通过邮递员或任何网络浏览器访问它。

@Override
public Map<?, ?> getData() {
    String url = "http://10.0.2.2:8000/rest/habits/";
    RequestQueue requestQueue = Volley.newRequestQueue(this.context);

    StringRequest jsonObjectRequest = new StringRequest(
            Request.Method.GET, url, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    String a = "1";
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle error
                    String a = "";
                }
            });

    requestQueue.add(jsonObjectRequest);

    return null;
}
}

我得到的唯一错误是“com.android.volley.ClientError”,这到底是怎么回事?

提前泰。

编辑:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.habits_builder_android">
    <uses-permission android:name="android.permission.INTERNET" />

    <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.Habits_builder_android">
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/Theme.Habits_builder_android.NoActionBar">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        </activity>
    </application>

</manifest>

它是 Android API 28。

回溯中唯一有用但我没有提到的是:E/Volley: [549] BasicNetwork.performRequest: Unexpected response code 400 for http://10.0.2.2:8000/rest/habits/

我知道,请求不好,但这是一个简单的获取,我已经在邮递员中复制/粘贴了标题并且它可以工作。

标签: androidapiresthttpandroid-emulator

解决方案


推荐阅读