soap发送报文请求和dom4j解析XML并且获得指定名称的节点信息

package com.lzw.b2b.soap;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DynamicSoapclientCall {
	
	private static Logger logger = LoggerFactory.getLogger(DynamicSoapclientCall.class);

	private String namespace;
    private String methodName;
    private String wsdlLocation;
    private String soapResponseData;

    public DynamicSoapclientCall(String namespace, String methodName, String wsdlLocation) {
        this.namespace = namespace;
        this.methodName = methodName;
        this.wsdlLocation = wsdlLocation;
    }

    public int invoke(Map<String, String> patameterMap) throws Exception {
        PostMethod postMethod = new PostMethod(wsdlLocation);
        String soapRequestData = buildRequestData(patameterMap);

        byte[] bytes = soapRequestData.getBytes("utf-8");
        InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                bytes.length, "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(requestEntity);

        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        soapResponseData = postMethod.getResponseBodyAsString();

        return statusCode;
    }

    private String buildRequestData(Map<String, String> patameterMap) {
        StringBuffer soapRequestData = new StringBuffer();
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""
                             + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
                             + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
        soapRequestData.append("<soapenv:Body>");
        soapRequestData.append("<" + methodName + " xmlns=\"" + namespace + "\">");
        soapRequestData.append("<" + methodName + "ln>");

        Set<String> nameSet = patameterMap.keySet();
        for (String name : nameSet) {
            soapRequestData.append("<" + name + ">" + patameterMap.get(name)
                    + "</" + name + ">");
        }
        
        soapRequestData.append("</" + methodName + "ln>");
        soapRequestData.append("</" + methodName + ">");
        soapRequestData.append("</soapenv:Body>");
        soapRequestData.append("</soapenv:Envelope>");
        logger.info("soapRequestData:"+soapRequestData.toString());
        return soapRequestData.toString();
    }
    
    public String getSoapResponseData() {
		return soapResponseData;
	}
        
    /**
	 * 获取文件的xml对象,然后获取对应的根节点root
	 */
	public static void getRoot(String xmlString) throws Exception {
		Document document = DocumentHelper.parseText(xmlString);
		final Element root = document.getRootElement();// 获取根节点
		getNodes(root);// 从根节点开始遍历所有节点
	}

	/**
	 * 从指定节点Element node开始,递归遍历其所有子节点
	 */
	@SuppressWarnings("unchecked")
	public static void getNodes(final Element node) {
		System.out.println("-------开始新节点-------------");
		// 当前节点的名称、文本内容和属性
		System.out.println("当前节点名称:" + node.getName());// 当前节点名称
		System.out.println("当前节点的内容:" + node.getTextTrim());// 当前节点内容
		final List<Attribute> listAttr = node.attributes();// 当前节点的所有属性
		for (final Attribute attr : listAttr) {// 遍历当前节点的所有属性
			final String name = attr.getName();// 属性名称
			final String value = attr.getValue();// 属性的值
			System.out.println("属性名称:" + name + "---->属性值:" + value);
		}
		// 递归遍历当前节点所有的子节点
		final List<Element> listElement = node.elements();// 所有一级子节点的list
		for (final Element e : listElement) {// 遍历所有一级子节点
			getNodes(e);// 递归
		}
	}
	
	@SuppressWarnings("unchecked")
    public List<Map<String,String>> loadAdPlayListMap(){
		try {
			 if (StringUtils.isNotBlank(adType) && adType.equals("13")) {
	            File adXmlFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "lzw.xml");
	            String adXml = FileUtils.readFileToString(adXmlFile, IHttpRequest.DEFAULT_CHARSET);
	            Document document = DocumentHelper.parseText(adXml);
	            Element element = document.getRootElement();
	            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
	            if (element != null) {
		            List<Element> itemElements = element.elements("item");
		            for (Element item : itemElements) {
			            List<Element> playerUrlElements = item.elements("playerUrl");
			            for (Element playerUrlElement : playerUrlElements) {
				            Map<String, String> map = new HashMap<String, String>();
				            map.put("type", playerUrlElement.attributeValue("type"));
				            map.put("duration", playerUrlElement.attributeValue("duration"));
				            map.put("name", playerUrlElement.attributeValue("name"));
				            String tag = playerUrlElement.attributeValue("tag");
				            map.put("tag", tag);
				            map.put("playerUrl", playerUrlElement.getTextTrim() + "&" + tag);
				            list.add(map);
			            }
		            }
		            this.adPlayListMap = list;
		            logger.debug("xml信息:{}",JsonUtils.objectToJson(this.adPlayListMap));
		            return adPlayListMap;
	            }
            }
        } catch (IOException e) {
	        e.printStackTrace();
        } catch (Exception e) {
	        e.printStackTrace();
        }
		return null;
	}
	
	public void parseXml() throws Exception {
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
	    			+ "<voole>"
				        + "<list>"
							+ "<epg>"
								+ "<title>hljgd</title>"
								+ "<price>48.88</price>"
							+ "</epg>"
							+ "<epg>"
						    	+ "<title mac=\"30026\">jndx</title>"
						    	+ "<price>39.95</price>"
					    	+ "</epg>"
				    	+ "</list>"
			    	+ "</voole>";
		Document doc = DocumentHelper.parseText(xml);
		Element database = (Element) doc.selectSingleNode("/voole/list/epg[2]");
		@SuppressWarnings("unchecked")
		List<Element> list = database.elements(); // 得到database元素下的子元素集合
		for (Element element : list) {
			// getName()是元素名,getText()是元素值
			System.out.println(element.getName() + ": " + element.getText());
		}
		List<?> fieldList = doc.selectNodes("//*[name()='title']");
		Iterator<?> fieldItr = fieldList.iterator();
		while (fieldItr.hasNext()) {
			Element fieldElement = (Element) fieldItr.next();
			System.out.println("当前 XPath: " + fieldElement.getPath());
			String fieldName = fieldElement.getText(); // field
			System.out.println(fieldName); // name
			String fieldClass = fieldElement.attributeValue("mac"); // field
			System.out.println(fieldClass);
		}
	}
    
    public static void main(String[] args) throws Exception {
        DynamicSoapclientCall dynamicHttpclientCall = new DynamicSoapclientCall(
                "http://webservice.lzw.shtel.com", "ServiceAuth",
                "http://1.1.1.1/LzwAuth");

        Map<String, String> patameterMap = new HashMap<String, String>();

        patameterMap.put("SPID", "1");
        patameterMap.put("UserID", "12");
        patameterMap.put("UserToken", "123");
        patameterMap.put("ProductID", "1234");
        patameterMap.put("ServiceID", "12345");
        patameterMap.put("ContentID", "123456");
        patameterMap.put("TimeStamp", "1234567");
        patameterMap.put("IP", "12345678");
        patameterMap.put("MAC", "123456789");
        patameterMap.put("TransactionID", "1234567890");

        String soapRequestData = dynamicHttpclientCall.buildRequestData(patameterMap);
        System.out.println(soapRequestData);

        int statusCode = dynamicHttpclientCall.invoke(patameterMap);
        if(statusCode == 200) {
        	logger.info("调用成功!");
        	System.out.println(dynamicHttpclientCall.soapResponseData);
        } else {
        	logger.info("调用失败!错误码:" + statusCode);
        }
    }
}

你可能感兴趣的:(soap发送报文请求和dom4j解析XML并且获得指定名称的节点信息)