首页 > 解决方案 > ESP32 Android App 通过 HTTP 通信

问题描述

我一直在尝试使用 ESP32 中的 SoftAP 和 Webserver 以及 android 中的 Volley 库将 ESP32 连接到我的 Android 应用程序。我可以从网络浏览器连接到 ESP32 网络服务器。但我无法通过 android volley 访问网页。我在 volley 中收到空错误响应。

我的手机可以连接到 SoftAP。

这是服务器的 ESP32 代码:

void setup()
{
  pinMode(pin_led, OUTPUT);
  Serial.begin(115200);
  SPIFFS.begin();

  wifiConnect();

  server.on("/l",[](){server.send_P(200,"text/html", webpage);});
  server.on("/toggle",toggleLED);
  server.on("/settings", HTTP_POST, handleSettingsUpdate);

  server.begin();
}

这是我的截击请求:

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url ="http://192.168.4.1/l";

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        Log.d("Connection", "Response: "+response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try{
                    Log.d("Connection", error.networkResponse.toString());
                } catch (Exception e){
                    Log.d("Connection", e.toString());
                }
            }
        });

// Add the request to the RequestQueue.
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                1,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

标签: androidandroid-volleywifiesp32

解决方案


问题似乎是因为奥利奥默认情况下未启用“明文流量”。一旦我在清单中添加了以下代码,它就可以工作了。

<activity android:name=".MainActivity" android:usesCleartextTraffic="true">

这个StackOverflow 对类似问题的回答中详细找到了解决方案。


推荐阅读