soap 实际操作

package com.tonbusoft.uums.demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tonbusoft.uums.commons.utils.JsonMsg;
import com.tonbusoft.uums.commons.utils.SendUtil;

@Controller
public class SoapController {
    private static Map<String,String> map = new HashMap<String,String>();  
     
    @RequestMapping("/soap/postSoap")
    public void postSoap(HttpServletRequest req, HttpServletResponse res) {
        String type = req.getParameter("type");
        String params = req.getParameter("params");
        if (null == type || null == params) {
            SendUtil.write(res, new JsonMsg(false, "参数错误"));
        }
        String url = req.getParameter("url");
        JsonMsg msg = new JsonMsg();
        InputStream is = null;
        OutputStream os = null;
        HttpURLConnection conn = null;
        
        if (null == type || null == params) {
            msg = new JsonMsg(false, "参数错误");
        } else {
            String[] items = params.split(";");
            
            try {
                String webUrl = req.getRequestURL().toString();
                int index = webUrl.indexOf("/soap/postSoap.do");
                webUrl = webUrl.substring(0,index);

                //服务的地址 ConfigBean.RootPath
                URL wsUrl = null;
                if (null == url || "".equals(url)) {
                    wsUrl = new URL(webUrl + "/webservice/myService/"+type+"?wsdl");
                } else {
                    wsUrl = new URL(url);
                }
                conn = (HttpURLConnection) wsUrl.openConnection();
                
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
                
                os = conn.getOutputStream();
                
                //请求体
                String data = "<?xml version='1.0' encoding='utf-8'?>"; 
                data += "<soap:Envelope ";
                data += "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
                data += "xmlns:xsd='http://www.w3.org/2001/XMLSchema' ";
                data += "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' >";
                data += "<soap:Body> ";
                data += "<m:" + type + " xmlns:m='http://service.webservice.uums.tonbusoft.com/'> ";
                for ( int i = 0; i < items.length; i++) {
                    String element = items[i];
                    String[] ele = element.split(",");
                    if (ele.length < 2) {
                        data += "<m:"+ ele[0] +"></m:"+ ele[0] +"> ";
                    } else {
                        data += "<m:"+ ele[0] +">"+ele[1]+"</m:"+ ele[0] +"> ";
                    }
                }
                data += "</m:"+type+"> ";
                
                os.write(data.getBytes());
                
                is = conn.getInputStream();
                
                byte[] b = new byte[1024];
                int len = 0;
                String s = "";
                String resultStr = "";
                while((len = is.read(b)) != -1){
                    String ss = new String(b,0,len,"UTF-8");
                    s += ss;
                }
                if (s.contains("error_token_validate")) {
                    resultStr = getErrorToken(type);
                } else {
                    resultStr = s;
                }
                
                msg = new JsonMsg(true, "soap success", paraXml(resultStr));
            } catch (Exception e) {
                try {
                    msg = new JsonMsg(false, "系统错误");
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != conn) {
                    conn.disconnect();
                }
            }
        }
        SendUtil.write(res, msg);
    }
    
    /** 
     * 解析 SOAP 消息 XML文件 递归 
     * @param element 
     * @author wyf 
     */  
    public static Map<String,String> readSoap(Element element){  
        if(element.elements().size()==0){  
            System.out.println(element.getName()+"="+element.getText());  
            return null;  
        }  
        for (Iterator<Element> iter=element.elementIterator();iter.hasNext();) {  
            Element ele=iter.next();  
            if(ele.getParent().getName().equalsIgnoreCase("BODY")){  
                System.out.println("body的子元素:"+ele.getName());  
            }  
            System.out.println(ele.getName()+"="+ele.getText().trim());  
            if(ele.elements().size()!=0){  
                readSoap(ele);  
            }  
            if(!"".equals(ele.getText().trim())&&ele.getText()!=null){  
                map.put(ele.getName(), ele.getText());  
            }  
        }  
        return map;  
    }  
    
    public static String changeToHtml(String soapData){  
        if(soapData!=null && !"".equals(soapData)){  
            soapData=soapData.replace("&lt;", "<");  
            soapData=soapData.replace("&gt;", ">");  
        }  
        return soapData;  
    } 
    
    public static String paraXml(String str) throws Exception{
        SAXReader reader = new SAXReader();
        // System.out.println(reader);
        // 注释:创建一个串的字符输入流
        StringReader in = new StringReader(str);
        Document doc = reader.read(in);
        // System.out.println(doc.getRootElement());
        // 注释:创建输出格式
        OutputFormat formater = OutputFormat.createPrettyPrint();
        //formater=OutputFormat.createCompactFormat();
        // 注释:设置xml的输出编码
        formater.setEncoding("utf-8");
        // 注释:创建输出(目标)
        StringWriter out = new StringWriter();
        // 注释:创建输出流
        XMLWriter writer = new XMLWriter(out, formater);
        // 注释:输出格式化的串到目标中,执行后。格式化后的串保存在out中。
        writer.write(doc);
 
        writer.close();
        
        return out.toString();
    }
    
    private String getErrorToken(String type){
        String errorToken = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
        errorToken += "<soap:Body><ns2:" + type + "Response xmlns:ns2='http://service.webservice.uums.tonbusoft.com/'><ns2:result>";
        errorToken += "token无效 请重新登录</ns2:result></ns2:" + type + "Response></soap:Body></soap:Envelope>";
        return errorToken;
    }
}
原文地址:https://www.cnblogs.com/xiaoSY-learning/p/6835726.html