记录对接webservice(报文格式)使用axis调用webservice,上传xml并返回xml,再通过dom4j解析返回的xml(相关jar包可以点我头像,找到我的下载,进行获取)
public static void main(String[] args) {
try {
String serverUrl = "http://xxxxxxxx?wsdl";//接口调用地址(这里的?wsdl可取可不取,不影响效果)
String xml="";
String result = "";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTimeout(new Integer(60000));
call.setTargetEndpointAddress(new URL(serverUrl));
String soapaction = "http://xxxxxxxxxxx.com/";// 命名空间
call.setOperationName(new QName(soapaction, "SendRecv"));//设置方法名
call.addParameter("sUser", XMLType.XSD_STRING, ParameterMode.IN);//方法参数,1参数名、2参数类型、3.入参 这里的参数类型要与wsdl中的参数类型保持一致
call.addParameter("sPwd", XMLType.XSD_STRING, ParameterMode.IN);//方法参数,1参数名、2参数类型、3.入参
call.setReturnType(XMLType.XSD_STRING);//设置返回值类型
//拼接XMl
String inBody = "<XMLDATA>" +
"<HEAD>" +
"<IP>192.168.0.214</IP>" +
"<MAC>"+localMacAddress1+"</MAC>" +
"<BZXX>1515924439799</BZXX>" +
"</HEAD>" +
"<MAIN>" +
"<QSRQ>20221205</QSRQ>" +
"<JZRQ>20221206</JZRQ>" +
"<YYBM>42505626100</YYBM>" +
"<DDLX></DDLX>" +
"<CGLX>1</CGLX>" +
"<DJTXF>1</DJTXF>" +
"<DDMXBH></DDMXBH>" +
"<DDMXBHCXTJ></DDMXBHCXTJ>" +
"</MAIN>" +
"</XMLDATA>" ;
String temp = formatXml(inBody);//转换成xml
//这里的xml根据项目的实际需求,如果需要xml类型就上传
Object[] c={sUser,sPwd,temp};//参数(这里的参数顺序,参数数量,和参数名称需要与上方call.addParameter中声明的一致,并与wsdl中的一致)
result = (String) call.invoke(c);//开始对接 (返回的是XML)
//解析xml,将xml转换成json--------------------------start
Document document = DocumentHelper.parseText(result);
Element rootElement = document.getRootElement();//获取到xml的根节点,即 XMLDATA
System.out.println("根节点:" + rootElement.getName());
Iterator iter = rootElement.elementIterator("HEAD");//获取根节点下的子节点HEAD
while(iter.hasNext()){
Element itemEle = (Element) iter.next();
String username = itemEle.elementTextTrim("JSSJ"); // 拿到head下的子节点script下的字节点username的值
String password = itemEle.elementTextTrim("ZTCLJG");
}
Iterator iters = rootElement.elementIterator("MAIN");//获取根节点下的子节点MAIN
while(iters.hasNext()){
Element itemEle = (Element) iters.next();
String sfwj = itemEle.elementTextTrim("SFWJ"); // 拿到MAIN下的字节点SFWJ的值
String jls = itemEle.elementTextTrim("JLS");
}
//end---------------------------------------------------------------
} catch (Exception e) {
}
}
public static String formatXml(String str) throws Exception {
Document document = null;
document = DocumentHelper.parseText(str);
// 格式化输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
StringWriter writer = new StringWriter();
// 格式化输出流
XMLWriter xmlWriter = new XMLWriter(writer, format);
// 将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
return writer.toString();
}