我想验证从httpResponse获得的XML响应。
我的代码
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(decouplingURL);
httpPost.setEntity(new StringEntity(soapRequest));
System.out.println(soapRequest);
HttpResponse httpResponse = httpclient.execute(httpPost);
System.out.println(httpResponse);
String resp = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
System.out.println(resp);
String payload = "";
NodeList nl = doc.getElementsByTagName("payload");
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
payload = nameElement.getFirstChild().getNodeValue().trim();
}
}在上面的代码中,我得到了以下响应,我想要获取@status并验证它的值是否为1。类似地,我必须验证weaher 'charge-method‘是否为3
<?xml version='1.0' encoding='UTF-8'?>
<er-response>
<payload>
<subscription id="33517965" status="1">
<pricepoint id="package:aceklpackage">
<charge-method>3</charge-method>
<rate resource="EUR" tax-rate="0.23">30.0</rate>
<user-group>hover32</user-group>
</pricepoint>
</subscription>
</payload>
</<er-response>发布于 2019-01-13 04:26:04
不确定这个问题与Apache有什么关系,您正在使用Apache HttpClient。您可以简单地使用XPath从xml中提取所需的元素:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resp.getBytes("UTF-8")));
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.printf("Status: %s\n", xPath.evaluate("//subscription/@status", doc));
System.out.printf("Charge Method: %s\n", xPath.evaluate("//charge-method//text()", doc));结果:
Status: 1
Charge Method: 3https://stackoverflow.com/questions/54162609
复制相似问题