Android rest ful webservice客户端无法正常运行

时间:2017-02-07 08:29:25

标签: android xml rest

我有一个RESTful Web服务,在浏览器中看起来像这样:

现在我想用我的智能手机访问这个 连接等工作但仍然无法正常工作。在浏览器中,我还收到以下消息:

this xml file does not appear to have any style information associated with it

我尝试以这种方式访问​​网络服务:

    InputStream in = null;
    String      s  = "";
    try {
        in = OpenHttpConnection(url);
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        try {
            db  = dbf.newDocumentBuilder();
            doc = db.parse(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        doc.getDocumentElement().normalize();

        NodeList defs = doc.getElementsByTagName("users");                     // iterate through <Definition>s
        for (int i=0; i<defs.getLength(); i++) {
            Node node = defs.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element)node;                                // convert Definition node into an element
                NodeList words = (e).getElementsByTagName("user"); // iterate through its <WordDefinition>s
                for (int j=0; j<words.getLength(); j++) {
                    Element we = (Element)words.item(j);
                    NodeList textNodes = ((Node) we).getChildNodes();
                    s += ((Node) textNodes.item(0)).getNodeValue() + ". \n";
                }
            }
        }
    } catch (IOException e1) {
        Log.d("NetworkingActivity", e1.getLocalizedMessage());
    }
    return s;    

虽然连接正常,但我得到了这个输出:

null.
null.
null.

1 个答案:

答案 0 :(得分:1)

使用以下代码段。

try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(in);

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("user");
            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;
                    s+= element2.getElementsByTagName("email").item(0).getChildNodes().item(0).getNodeValue();

                }
            }//end of for loop
            System.out.print(s);
        } catch (Exception e) {e.printStackTrace();}