如何创建SOAP Request,简单方法

时间:2014-06-03 10:42:06

标签: java xml web-services soap jaxb

我是SOAP的新手,
我正在硬编码SOAP请求并发送到服务器,它工作正常。现在我想动态创建SOAP请求,因为我是SOAP新手,我不知道  要准备XML我使用jaxb,我应该使用相同的方法来创建SOAP请求还是有更好的方法?

我的Java代码

public class Test {

public static void main(String[] args) {

    String xml ="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n"
            + "   <soapenv:Header/>\n"
            + "   <soapenv:Body>\n"
            + "      <tem:RequestData>\n"
            + "         <!--Optional:-->\n"
            + "         <tem:requestDocument>\n"
            + "\n"
            + "\n"
            + "<![CDATA[ <Request>\n"
            + "<Authentication CMId='68' Guid='5594FB83-F4D4-431F-B3C5-EA6D7A8BA795' Password='poihg321TR' Function='1' />\n"
            + "<Establishment Id='4297867' >\n"
            + "</Establishment>\n"
            + "</Request> ]]> \n"
            + "\n"
            + "\n"
            + "</tem:requestDocument>\n"
            + "      </tem:RequestData>\n"
            + "   </soapenv:Body>\n"
            + "</soapenv:Envelope>";




    sendRequestToChannel(xml);
}

private static String sendRequestToChannel(String request) {

    String xmlData = null;
    BufferedReader rd = null;
    BufferedWriter bw = null;
    String line = null;
    String lineSep = null;
    String data = null;
    StringBuffer serverData = null;
    int SOCKET_TIMEOUT = 6000, PORT = 80;
    String HOST = null,PATH=null;


    try {

        java.net.URL url = new java.net.URL("http://pp.hotels.travelrepublic.co.uk/ChannelManager.svc");
        HOST=url.getHost();
        PATH=url.getPath();
        Socket cliSocket = new Socket();
        cliSocket.connect(new InetSocketAddress(HOST, PORT), SOCKET_TIMEOUT);
        bw = new BufferedWriter(new OutputStreamWriter(cliSocket.getOutputStream()));

        bw.write("POST " + PATH + " HTTP/1.0");
        bw.write("\r\n");
        bw.write("Accept-Encoding: gzip,deflate");
        bw.write("\r\n");
        bw.write("Content-Type: text/xml;charset=UTF-8");
        bw.write("\r\n");
        bw.write("SOAPAction: http://tempuri.org/IPublicChannelManagerService/RequestData");
        bw.write("\r\n");
        bw.write("Content-Length: " + request.length() + "\r\n");
        bw.write("Host: " + HOST + "\r\n");
        bw.write("Proxy-Connection: Keep-Alive\r\n");
        bw.write("User-Agent: Apache-HttpClient/4.1.1 (java 1.5)\r\n");
        bw.write("\r\n");
        bw.write(request);
        bw.flush();

        rd = new BufferedReader(new InputStreamReader(cliSocket.getInputStream()));

        serverData = new StringBuffer("");

        lineSep = System.getProperty("line.separator");
        while ((line = rd.readLine()) != null) {
            serverData.append(line);
            serverData.append(lineSep);
        }

        data = serverData.toString();

        int index = data.indexOf("<");

        if (index != -1) {
            xmlData = data.substring(index);
            System.out.println("\r\n \r\n  XML Data \r\n  "+xmlData);
        } else {
            System.out.println("\r\n \r\n  XML Data Not Retrived");
        }


    } catch (java.net.UnknownHostException uh) {
        uh.printStackTrace();
        System.out.println("$$$$$$$$$$$$  in sendRequestToChannel : UnknownHostException " + uh.getMessage());
        return "   in sendRequestToChannel : UnknownHostException " + uh.toString();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("$$$$$$$$$$$$  in sendRequestToChannel :  IOException " + ioe.getMessage());
        return " in sendRequestToChannel :   IOException " + ioe.toString();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("$$$$$$$$$$$$  in sendRequestToChannel :  Exception " + e.getMessage());
        return " in sendRequestToChannel :  Exception " + e.toString();
    } finally {
        try {
            if (bw != null) {
                bw.close();
            }
        } catch (IOException ex) {
        }
        try {
            if (rd != null) {
                rd.close();

            }
        } catch (IOException ex) {
        }

        bw = null;
        rd = null;
        line = null;
        lineSep = null;
        data = null;
        serverData = null;

    }
    return xmlData;
}
}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

尝试使用'javax.xml.soap'包的类。

public String cretaeSOAPMessage(Document soapBodyDoc, String serverURI,
        String soapAction, String bodyNameSpace) {
    String soapMsg = null;      
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();


        SOAPBody soapBody = envelope.getBody(); 
        soapBody.addNamespaceDeclaration("tem", bodyNameSpace);
        soapBody.addDocument(soapBodyDoc);          


        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", serverURI + soapAction);;

        soapMessage.saveChanges();


        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            soapMessage.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        soapMsg = new String(out.toByteArray());


    } catch (SOAPException e) {
        e.printStackTrace();
    }

    return soapMsg;
}

soapBodyDoc:org.w3c.dom.Document表示

中的数据

serverURI:您的目标名称空间

soapAction:wsdl:operation

bodyNameSpace:“http://tempuri.org/

不能说它是否比JAXB更好。但是在你的其他帖子中我可以看到你正在努力使用JAXB包含CDATA部分。这个逻辑可能会帮助你摆脱它。

有时候你可能会遇到一些问题

soapBody.addDocument(soapBodyDoc);

如果是这样,不是将整个身体内容添加为文档,而是在其中创建身体。 为此,请使用以下代码示例

SOAPElement soapBodyElem = soapBody.addChildElement("RequestData", "tem");
soapBodyElem.addChildElement("requestDocument","tem");

soapBodyElem.addTextNode("<![CDATA[ <Request>....");