Форматирование пространства имен XML в Java

API, на который мы отвечаем, ожидает следующий XML:

<soapenv:Envelope  >
  <soapenv:Header/>
  <soapenv:Body>
     <api:Response>Result received successfully</api:Response>
  </soapenv:Body>
</soapenv:Envelope>

Наша реализация Java производит следующий XML:

<SOAP-ENV:Envelope  >
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<api:Response>Result received successfully</api:Response>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Они не хотят дефис в XML.

Ниже приведен код, который создает наше возвращаемое значение:

        MessageFactory messageFactory;
        try {

            messageFactory = MessageFactory.newInstance();
            SOAPMessage soapMessage = messageFactory.createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            //String SOAP_PREFIX = "soapenv";//yamin
            String apiURI = "http://schemas.xmlsoap.org/soap/envelope/";

            // SOAP Envelope
            SOAPEnvelope envelope = soapPart.getEnvelope();
            envelope.addNamespaceDeclaration("api", apiURI);

            // SOAP Body
            SOAPBody soapBody = envelope.getBody();
            SOAPElement soapBodyRequestElem = soapBody.addChildElement("Response", "api");
            soapBodyRequestElem.addTextNode("Result received successfully");

            MimeHeaders headers = soapMessage.getMimeHeaders();
            headers.addHeader("SOAPAction", apiURI  + "api");
            ///envelope.setPrefix(SOAP_PREFIX);//yamin
            soapMessage.saveChanges();

            /* Print the request message */
            System.out.print("Request SOAP Message Starting at : " + System.currentTimeMillis());
            soapMessage.writeTo(System.out);
            System.out.println();

            ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
            soapMessage.writeTo(byteOutStream);
            String reqmessage = new String(byteOutStream.toByteArray());

            System.out.println (reqmessage);

            writer.append(reqmessage);
            writer.close();

Может ли кто-нибудь подсказать нам, как настроить наш код, чтобы вернуть ожидаемый формат?

2 ответа

  1. Вы должны прочитать эту тему

    если вы действительно хотите изменить префикс SOAP-ENV попробуйте этот код :

    package projetPourTest;
    
    import static org.junit.Assert.*;
    
    import java.io.ByteArrayOutputStream;
    
    import javax.xml.soap.MessageFactory;
    import javax.xml.soap.MimeHeaders;
    import javax.xml.soap.SOAPBody;
    import javax.xml.soap.SOAPConstants;
    import javax.xml.soap.SOAPElement;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPException;
    import javax.xml.soap.SOAPMessage;
    import javax.xml.soap.SOAPPart;
    
    import org.junit.Test;
    
    public class SoapMessageTest {
    
        @Test
        public void test() throws Exception {
            MessageFactory messageFactory;
    
            messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
            SOAPMessage soapMessage = messageFactory.createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            //String SOAP_PREFIX = "soapenv";//yamin
            String apiURI = "http://blah.blah.blah";
    
            // SOAP Envelope
            SOAPEnvelope envelope = soapPart.getEnvelope();
            System.out.println(envelope.getPrefix());
            envelope.setPrefix("soap");
            System.out.println(envelope.getPrefix());
            envelope.addNamespaceDeclaration("api", apiURI);
    
            // SOAP Body
            SOAPBody soapBody = envelope.getBody();
            SOAPElement soapBodyRequestElem = soapBody.addChildElement("Response", "api");
            soapBodyRequestElem.addTextNode("Result received successfully");
    
            /* Print the request message */
            System.out.println("Request SOAP Message Starting at : " + System.currentTimeMillis());
    
            ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
            soapMessage.writeTo(byteOutStream);
            String reqmessage = new String(byteOutStream.toByteArray());
    
    
            System.out.println (reqmessage);
            fail("Not yet implemented");
        }
    
    }
    
  2. Необходимо установить префикс. Код, который вы опубликовали, прокомментировал разделы yamin, которые будут работать.

    MessageFactory messageFactory;
        try {
    
            messageFactory = MessageFactory.newInstance();
            SOAPMessage soapMessage = messageFactory.createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            //String SOAP_PREFIX = "soapenv";//yamin
            String apiURI = "http://schemas.xmlsoap.org/soap/envelope/";
    
            // SOAP Envelope
            SOAPEnvelope envelope = soapPart.getEnvelope();
            envelope.addNamespaceDeclaration("api", apiURI);
    
            // SOAP Body
            SOAPBody soapBody = envelope.getBody();
            SOAPElement soapBodyRequestElem = soapBody.addChildElement("Response", "api");
            soapBodyRequestElem.addTextNode("Result received successfully");
    
            MimeHeaders headers = soapMessage.getMimeHeaders();
            headers.addHeader("SOAPAction", apiURI  + "api");
            ///envelope.setPrefix(SOAP_PREFIX);//yamin
    
            // Setting the prefixes
            String SOAP_PREFIX = "soapenv";//yamin
            envelope.setPrefix(SOAP_PREFIX);
            soapMessage.getSOAPHeader().setPrefix(SOAP_PREFIX);
            soapBody.setPrefix(SOAP_PREFIX);
    
            soapMessage.saveChanges();
    
            /* Print the request message */
            System.out.print("Request SOAP Message Starting at : " + System.currentTimeMillis());
            soapMessage.writeTo(System.out);
            System.out.println();
    
            ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
            soapMessage.writeTo(byteOutStream);
            String reqmessage = new String(byteOutStream.toByteArray());
    
            System.out.println (reqmessage);
    
            writer.append(reqmessage);
            writer.close();