java发送soap请求和解析soap的响应

java发送soap请求和解析soap的响应

  • 一.soap请求报文
  • 二.soap响应报文
  • 三.代码实现
    • 1.引入对应jar
    • 2.代码实现

一.soap请求报文

<s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <GetPoints xmlns="http://tempuri.org/">
            <kunkun xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
            	
                <d4p1:string>changd4p1:string>  
                <d4p1:string>tiaod4p1:string>  
                <d4p1:string>rapd4p1:string>  
                <d4p1:string>basketballd4p1:string>                
            kunkun>
        GetPoints>
    s:Body>
s:Envelope>

二.soap响应报文

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <GetPointsResponse xmlns="http://tempuri.org/">
            <GetPointsResult xmlns:a="http://schemas.datacontract.org/2004/07/XDB.DataServiceInterface" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <a:Data>
                    <a:Name>张三a:Name>
                    <a:LikeYear>2.5年a:LikeYear>        
                a:Data>
                <a:Data>
                    <a:Name>李四a:Name>
                    <a:LikeYear>2.5年a:LikeYear>        
                a:Data>
                <a:Data>
                    <a:Name>王二a:Name>
                    <a:LikeYear>2.5年a:LikeYear>        
                a:Data>
                <a:Data>
                    <a:Name>麻子a:Name>
                    <a:LikeYear>2.5年a:LikeYear>        
                a:Data>
            GetPointsResult>
        GetPointsResponse>
    s:Body>
s:Envelope>

三.代码实现

1.引入对应jar

   <dependency>
	   <groupId>dom4jgroupId>
	   <artifactId>dom4jartifactId>
    dependency>

2.代码实现

public boolean testSoap() {
        StringBuilder result = new StringBuilder();
        OutputStream out = null;
        BufferedReader in = null;
        //需要传的参数
        String[] pointNames = {"chang","tiao","rap","basketball"};
        //拼接请求报文的方法
        String soap = buildXML(pointNames);
        try {
            URL url = new URL(你需要请求的url地址);
            URLConnection connection = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) connection;
            byte[] b = soap.getBytes("ISO-8859-1");
            httpConn.setRequestProperty( "Content-Length",String.valueOf( b.length ) );
            httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
            httpConn.setRequestProperty("soapaction","http://tempuri.org/WcfDataProxy/GetPoints");//重点中的重点,不加就500。注意:soapaction对应的值不固定,具体值看你的请求。
            httpConn.setRequestMethod( "POST" );
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);

            out = httpConn.getOutputStream();
            out.write( b );
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));

            //把响应回来的报文拼接为字符串
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                result.append(inputLine);
            out.close();
            in.close();
            //把soap的xml报文转为list
            Document doc = DocumentHelper.parseText(result.toString());//报文转成doc对象
            Element root = doc.getRootElement();//获取根元素,准备递归解析这个XML树
            Map<String, String> map = new HashMap<String, String>();
            List<Map<String, String>> lists = new ArrayList<Map<String, String>>();//存放叶子节点数据
            //获取叶子节点的方法
            getCode(root, map,lists);
            //循环叶子节点数据
            for (Map<String, String> item : lists) {
                //取响应报文中的name
                String key = item.get("Name");
                //取响应报文中的LikeYear
                String value =  item.get("LikeYear");
                //你需要的后续操作
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }  catch (ParseException e) {
            e.printStackTrace();
        } catch (org.dom4j.DocumentException e) {
            e.printStackTrace();
        } finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return true;
    }


   /**
     * 拼接报文
     * @param pointNames
     * @return
     */
    private static String buildXML(String[] pointNames){

        String str = " +
                "    xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "    \n" +
                "         +
                "            xmlns=\"http://tempuri.org/\">\n" +
                "             +
                "                xmlns:d4p1=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"\n" +
                "                xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
        for (String s : pointNames) {
            str += "" + s + ""+"\n";
        }
        str += "\n" +
                "        \n" +
                "    \n" +
                "";

        return str;
    }

	 /**
     * 找到soap的xml报文的叶子节点的数据
     * @param root
     * @param map
     * @param lists
     */
    public static void getCode(Element root, Map<String, String> map,List<Map<String, String>> lists) {
        if (root.elements() != null) {
            List<Element> list = root.elements();//如果当前跟节点有子节点,找到子节点
            for (Element e : list) {//遍历每个节点
                if (e.elements().size() > 0) {
                    getCode(e, map ,lists);//当前节点不为空的话,递归遍历子节点;
                }
                if (e.elements().size() == 0) {
                    //如果为叶子节点,那么直接把名字和值放入map
                    map.put(e.getName(), e.getTextTrim());
                    //如果数据都放进map,那就存进list
                    if (map.size() == 2){ //注意:因为这里我响应回来的叶子节点是两个,所以等于2,如果你的不是请修改。对应的就是这是两个叶子节点
                        Map<String, String> mapTo = new HashMap<String, String>();
                        //map全部赋值给maoTo
                        mapTo.putAll(map);
                        lists.add(mapTo);
                        //清空map
                        map.clear();
                    }
                }
            }
        }
    }

你可能感兴趣的:(java,python,开发语言,soap协议,xml)