Android 互联网访问抛出 IOException

Android internet access throws IOException

我正在尝试编写一个应用程序来 ping 一个网页,然后触发一个动作。

package com.anton.lightcontrol;

import android.graphics.Color;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {

    Switch onOffSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onOffSwitch = (Switch) findViewById(R.id.onOffSwitch);
        onOffSwitch.setChecked(true);
        onOffSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onOffSwitch.isChecked()==true) {
                    onOffSwitch.setTextColor(Color.GREEN);
                    LightConnection("http://raspberrypi/toggle_on.py");



                }
                else if (onOffSwitch.isChecked()==false){
                    onOffSwitch.setTextColor(Color.RED);
                    LightConnection("http://raspberrypi/toggle_off.py");

                }
            }
        });
    }

    private void LightConnection(final String accessUrl){
        (new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                Log.d("EXEC", "#1");
                URL url = new URL(accessUrl);
                Log.d("EXEC", "#2");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                Log.d("EXEC", "#3");

                InputStreamReader input = new InputStreamReader(conn.getInputStream(), "utf-8");
                Log.d("EXEC", "#4");

                BufferedReader reader = new BufferedReader(input,2000);
                Log.d("EXEC", "#5");
                String line = reader.readLine();
                Log.d("EXEC", "#6");


            }
                catch (IOException e){
                    Log.d("EXEC", "#10 - CATCH");
                    onOffSwitch.setTextColor(Color.YELLOW);
                }

            }
        })).start();
    }
}

我的调试输出如下所示:

D/EXEC: #1
D/EXEC: #2
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/EXEC: #3
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/EXEC: #10 - CATCH

我一直在寻找 isSBSettingEnabled false 错误的解决方案,但找不到任何对我有帮助的方法。

我 运行 我的应用程序在三星 M20 智能手机上。

这在技术上不是错误,因为它提醒您您没有使用网络安全配置。此处有更多相关信息:Network security configuration: Android Developer Docs.

但是,如果您仅限于使用 HTTP,则可以通过将此添加到 AndroidManifext.xml 中的 <application> 标记来允许明文流量来解决连接问题:

android:usesCleartextTraffic="true"