I need to be able to clone a SOAPMessage object, but it doesn't implement Clonable. How can I do this?

笑着哭i 提交于 2019-12-25 03:33:07

问题


I have a "skeleton" SOAPMessage object, which will be the starting point of other SOAPMessages. I want to be able to clone the base SOAPMessage, so I can then fill it with the information needed and send it, and do this every time I need to send a SOAPMessage.
How can I clone a SOAPMessage, since it doesn't implement Clonable? I've been looking for other frameworks and found Apache CXF, which has a SoapMessage class that is Clonable. However, I can't use it because the WSDL I'm using is old-style (encoded, or something) and doesn't allow me to import the WSDL into Java classes...
Any suggestions? Thanks in advance!


回答1:


You can simply change SOAPMessage to string, and use this string as a source for new instance message.

Example below.

public static String messageToString(SOAPMessage soap) throws  SOAPException, IOException{
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    soap.writeTo(stream);
    String message = new String(stream.toByteArray(), "utf-8");
    return message;
}

public static SOAPMessage stringToMessage(String soap) throws IOException, SOAPException{
    InputStream inputStream = new ByteArrayInputStream(soap.getBytes());
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(null, inputStream);
    return soapMessage;
}

SOAPMessage sourceMessage; //some message to clone need to initiate it
SOAPMessage clonedMessage = MessageFactory.newInstance().createMessage();
clonedMessage = stringToMessage(messageToString(sourceMessage));

Work for me.



来源:https://stackoverflow.com/questions/30710536/i-need-to-be-able-to-clone-a-soapmessage-object-but-it-doesnt-implement-clonab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!