HttpURLConnection类(连接不成立) [英] HttpURLConnection (Connection not established)

查看:262
本文介绍了HttpURLConnection类(连接不成立)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是在 GETRESPONSE code 抛出异常,也为 urlConnection.getInputStream()(如果开关壳体不使用)。谁能告诉我为什么不能够建立连接使用 HttpURLConnection类和错误在我的code。

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.

推荐答案

听起来像是本地的网站是不是通过你的设备进行访问。
找到问题,或使其可以运行在设备上,然后再试一次它会工作相同的步骤。
如果使用本地网站的Andr​​oid程序在本地的网站必须经由被用于测试的设备访问。所以LAN网络上正确配置站点和连接设备同一个网络上。

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.

这篇关于HttpURLConnection类(连接不成立)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆