Android客户端解析web服务器XML数据小问题

Android客户端解析web服务器XML数据

通过Pull 解析方式实现

代码如下:

private void sendXMLtWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection con = null;
                try {

                    URL url = new URL("http://192.168.1.107:8062/get_data.xml");
                    con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("GET");
                    con.setConnectTimeout(8000);
                    con.setReadTimeout(8000);
                    int responseCode = con.getResponseCode();
                    if (responseCode == 200) {
                        InputStream in = con.getInputStream();
                        parseXML(in);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }).start();

    }
    private void parseXML(InputStream in) {
        XmlPullParser pullParser = Xml.newPullParser();
        try {
            pullParser.setInput(in, "UTF-8");
            int eventType = pullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != pullParser.END_DOCUMENT) {
                String nodeName = pullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG: {
                        if ("id".equals(nodeName)) {
                            id = pullParser.nextText();
                        }
                        if ("name".equals(nodeName)) {
                            name = pullParser.nextText();
                        }
                        if ("version".equals(nodeName)) {
                            version = pullParser.nextText();
                        }
                        break;
                    }
                    case XmlPullParser.END_TAG: {
                        if ("app".equals(nodeName)) {
                            Log.d("MainActivity", "id:" + id);
                            Log.d("MainActivity", "name:" + name);
                            Log.d("MainActivity", "version:" + version);
                        }
                        break;
                    }
                    default:
                        break;
                }
                eventType = pullParser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

期间xml的访问报一个下面这样的错

java.net.ConnectException: failed to connect to /127.0.0.1 (port 8062) after 8000ms: isConnected failed: ECONNREFUSED (Connection refused)


加上权限查看代码找了很久发现不了原因,经过显示测试,原来是访问不到这个页面

但是在电脑上面是可以访问到的

查了下搜索引擎原来要保证两者之间处于同一网段

好像是模拟器可以用10.0.2.2代替

我用的真机测试要改为ip地址就没有报错了。

localhost或者127.0.0.1是不能访问的,会报以上这个错误。

你可能感兴趣的:(随笔记录,Android日记)