请求xml,解析xml通过实列直接上手
一、依赖包
需要导入dom4j包
下载地址:🛫飞机路径
二、实列方法以及思路
/** 调用外部接口*/
@Test
public void analysisXml(){
String xml = getHttpProductApi();
try {
//将xml转编码 如果不转有可能出现乱码
xml = new String(xml.getBytes("GBK"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
Document document = DocumentHelper.parseText(xml);
// 转编码
document.setXMLEncoding("utf-8");
//获取到最大的节点 Request
Element root = document.getRootElement();
//获取 Header 的节点信息
Element header = root.element("Header");
//获取 ProductResponse 商品响应数据
Element productResponse = root.element("ProductResponse");
//获取多个相同子节点
Iterator otherInfo = productResponse.elementIterator("OtherInfo");
while (otherInfo.hasNext()){
// 获取相同第一个标签
Element itemEle = (Element) otherInfo.next();
// 获取标签属性值
List<DefaultAttribute> attributes1 = itemEle.attributes();
for (DefaultAttribute attr : attributes1){
System.out.println(itemEle.getName()+":[ nodeName:"+attr.getName()+" nodeValue:"+ attr.getStringValue()+" stringValue:"+itemEle.getText()+"]\n");
}
}
// String SourceSystem = header.elementText("SourceSystem");
// String MessageID = header.elementText("MessageID");
//
// //获取 Body--->CT_MedicineMaterialList--->CT_MedicineMaterial 的节点信息
// Element body = root.element("Body").element("CT_MedicineMaterialList").element("CT_MedicineMaterial");
} catch (DocumentException e) {
e.printStackTrace();
}
}
// 请求xml参数
public String getHttpProductApi(){
String url = ".....";
String xmlHeader=
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<PriceAvailabilityRequest>\n" +
"\t<Header>\n" +
"\t\t<MessageId>WUXIAPPTEC-2021-11-08 13:25:15.072</MessageId>\n" +
"\t\t<Timestamp>2021-11-08 13:25:15.072</Timestamp>\n" +
"\t</Header>\n" +
"\t<RequesterInfo>\n" +
"\t\t<Customer code=\"WUXIAPPTEC_PACN\"/>\n" +
"\t\t<Location code=\"CN\"/>\n" +
"\t\t<PreferredLanguage>EN</PreferredLanguage>\n" +
"\t\t<PreferredCountry>CN</PreferredCountry>\n" +
"\t</RequesterInfo> \n" +
"\t\t<ProductRequest itemNumber=\"1\"> \n" +
"\t\t\t<SupplierPartNumber>195030-100ML</SupplierPartNumber> \n" +
"\t\t\t<UnitOfMeasure unit=\"\"/> \n" +
"\t\t\t<Quantity>1</Quantity> \n" +
"\t\t</ProductRequest>\n" +
"</PriceAvailabilityRequest>";
String returnMsg = post(url, xmlHeader);
System.out.println(returnMsg);
return returnMsg;
}
// 请求外部接口POST
public String post(String url, String xmlFileName) {
//关闭
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");
//创建httpclient工具对象
HttpClient client = new HttpClient();
//创建post请求方法
PostMethod myPost = new PostMethod(url);
//设置请求超时时间
client.setConnectionTimeout(300 * 1000);
String responseString = null;
try {
//设置请求头部类型
myPost.setRequestHeader("Content-Type", "text/xml");
myPost.setRequestHeader("charset", "utf-8");
//设置请求体,即xml文本内容,注:这里写了两种方式,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式
// 1.xml文本内容
myPost.setRequestBody(xmlFileName);
// 2.xml文件
// InputStream body = this.getClass().getResourceAsStream("/" + xmlFileName);
// myPost.setRequestBody(body);
// myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));
int statusCode = client.executeMethod(myPost);
if (statusCode == HttpStatus.SC_OK) {
BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
byte[] bytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int count = 0;
while ((count = bis.read(bytes)) != -1) {
bos.write(bytes, 0, count);
}
byte[] strByte = bos.toByteArray();
responseString = new String(strByte, 0, strByte.length, "utf-8");
bos.close();
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
myPost.releaseConnection();
return responseString;
}
如果报错:java.io.FileNotFoundException: 项目路径\xxx.xx (系统找不到指定的文件。)
在项目路径下加缺少的文件