HttpURLConnection(未建立连接)

HttpURLConnection (Connection not established)

try{
    String a="http://10.0.2.2/test2.php";
    Log.d("URL",a);
    url = new URL(a);
    Log.d("URL23",a);

    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    Log.d("URL3",a);

    try {
        System.setProperty("http.keepAlive", "false");
        // just want to do an HTTP GET here
        urlConnection.setRequestMethod("GET");

        urlConnection.setRequestProperty("Content-length", "0");
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);
        // give it 15 seconds to respond
        urlConnection.setReadTimeout(35 * 1000);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
            case 200:Log.d("CASE","@@@@@@@@@@@@@@@@       200");
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                Log.d("CASE 201 String",sb.toString());
        }
    }
}

它在 getResponseCodeurlConnection.getInputStream() 处抛出异常(如果未使用 switch case)。谁能告诉我为什么我无法使用 HttpURLConnection 和我的代码中的错误来建立连接。

听起来您的本地网站无法通过您的设备访问。 找到问题或让它在您的设备上运行,然后再试一次相同的程序。 如果您使用带有 android 编程的本地网站,则必须可以通过用于测试的设备访问本地网站。因此,请在 LAN 网络上正确配置站点并将您的设备连接到同一网络。