您的位置:首页 > 编程语言 > Java开发

java 发送 soap 消息 返回xml格式字符串

2014-11-12 19:15 393 查看
private static final String NAMESPACE_URI = "http://tempurl.org/";
private static final String CONTENT_TYPE = 

private static final String HIS_SERVICE_KEY = 
private static final String HIS_SERVICE_URL = 

SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance(); 

SOAPConnection connection = soapConnFactory.createConnection(); 

MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); 
SOAPMessage message = messageFactory.createMessage(); 
 
MimeHeaders hd = message.getMimeHeaders(); 
   hd.setHeader("Content-Type", CONTENT_TYPE); 
   hd.addHeader("SOAPAction", NAMESPACE_URI + methodName); 
   
   
   SOAPPart soapPart = message.getSOAPPart(); 

        //Create objects for the message parts            

        SOAPEnvelope envelope = soapPart.getEnvelope();     

        SOAPBody body = envelope.getBody(); 

       

       //创建根节点填充Soap body。

        SOAPElement bodyElement = body.addChildElement(envelope.createName(methodName, null, NAMESPACE_URI)); 

        

        Collection<String> c = params.values();

        Set<String> keys = params.keySet();

        for (Iterator it = keys.iterator(); it.hasNext();) {

            String paramKey = (String) it.next();

            String paramValue = params.get(paramKey);

            bodyElement.addChildElement(paramKey).addTextNode(paramValue); 

        }

 

        //保存message

        message.saveChanges(); 

        logger.debug("\\nREQUEST:\\n" + message);

        

        //发送请求获取相应

        String destination = HIS_SERVICE_URL; 

        SOAPMessage reply = connection.call(message, destination); 

        logger.debug("\\nREQUEST:\\n" + message);

        //Create the transformer 

        TransformerFactory transformerFactory = TransformerFactory.newInstance(); 

        Transformer transformer = transformerFactory.newTransformer(); 

       

        //提取响应的xml

        Source sourceContent = reply.getSOAPPart().getContent(); 

        

        //Set the output for the transformation 

        StreamResult result = new StreamResult(System.out); 

        transformer.transform(sourceContent, result); 

        logger.debug("\\nRESPONSE:\\n" + result); 

        

        String response = reply.getSOAPBody().getTextContent();     

        
        return response;

返回的response可以解析成dom对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐