HttpURLConnection (Connection not established)

北城余情 提交于 2019-12-12 01:38:47

问题


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());
        }
    }
}

It is throwing an exception at getResponseCode and also at urlConnection.getInputStream() (if switch case not used). Can anyone please tell why i am not able to set up connection using HttpURLConnection and error in my code.


回答1:


Sounds like your local website is not accessible through your device. Find the issue or make it runnable on your device then try again the same procedure it will work. If you use local website with the android programming the local website must be accessible via the device which is used for testing. So configure the site properly on LAN Network and connect your device on same network.



来源:https://stackoverflow.com/questions/30595347/httpurlconnection-connection-not-established

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!