1

我正在开发一个用于在线投票的应用程序,其中登录过程是通过 dotnet 中的 web 服务进行的。网络服务部分已准备就绪并且可以工作,但我想看看返回了什么响应。

URL url=new URL("http://www.example.com/login");
            HttpURLConnection urlconnection=(HttpURLConnection)url.openConnection();
            String requestXML="<data><username>sachin.t@gmail.com</username><password>sachin</password></data>";
            urlconnection.setRequestMethod("POST");
            urlconnection.setDoInput(true);
            urlconnection.setDoOutput(true);
            urlconnection.setRequestProperty("Accept-Charset", "UTF-8");
            urlconnection.setRequestProperty("Content-type", "application/xml");
            urlconnection.setRequestProperty("Content-Length", ""+Integer.toString(requestXML.length()));

            //Send request
            DataOutputStream dout=new DataOutputStream(urlconnection.getOutputStream());
            dout.writeBytes(requestXML);
            dout.flush();
            dout.close();
            if(urlconnection.getResponseCode()==HttpURLConnection.HTTP_OK)
            {
                InputStream is=urlconnection.getInputStream();
                BufferedReader breader=new BufferedReader(new InputStreamReader(is));
                String temp;
                String resp="";
                while((temp=breader.readLine())!=null)
                {
                    resp+=temp;
                }



                Document respdoc=null;
                DocumentBuilderFactory docbuilderfactory=DocumentBuilderFactory.newInstance();
                DocumentBuilder docbuilder=docbuilderfactory.newDocumentBuilder();
                InputSource isource=new InputSource();
                isource.setCharacterStream(new StringReader(resp));
                respdoc=docbuilder.parse(isource);

从网上我得到了这个,但我想解析下面给出的响应。

<login>
    <login_validation>"1/2/3"</login_validation> 
    ( 1-invalid username,2-successfull and 3- already voted)

    <voter_id>" 0/voter_id "</voter_id> 
    (if sucessfull then only voter_id else value will return 0)
</login>

有什么建议吗?

先感谢您。

4

1 回答 1

1

您可以使用 Xpath (http://developer.android.com/reference/javax/xml/xpath/package-summary.html)。如果我的回答正确,您的回答是“respdoc”。要选择 login_validation 节点,您必须这样做:

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/login/login_validation";
Node loginValidation = (Node) xpath.evaluate(expression, respdoc, XPathConstants.NODE);

选择 voter_id 节点:

expression = "/login/voter_id";
Node voterId = (Node) xpath.evaluate(expression, respdoc, XPathConstants.NODE);

之后,您可以使用 loginValidation 和 voterId 做任何您想做的事情。

于 2013-01-26T19:10:23.970 回答