如何在java中准备SOAP Request并调用Web服务

时间:2014-06-20 14:14:13

标签: java web-services soap

我是SOAP新手,我想调用Web服务 我看过制作肥皂的教程 这是代码

    MessageFactory mf = null;
    SOAPMessage sm = null;
    SOAPEnvelope envelope = null;
    MimeHeaders headers = null;
    SOAPBody body = null;
    SOAPElement requestData = null;
    SOAPElement requestDoc = null;
    CDATASection cdata = null;
    SOAPConnectionFactory sfc = null;
    SOAPConnection connection = null;
    URL requestUrl = null;
    SOAPMessage response = null;
    OutputStream os = null;
    String host = null;
    int port = 80;
    String path = null;
    String api_key = null;
    int socket_timeout = 0;
    String service_type = null;
    String baseXml = null;

    try {

        xmlChannelRequest = createChannelRequest(cmId, function, guId, password, estabId);

        mf = MessageFactory.newInstance();
        sm = mf.createMessage();
        envelope = sm.getSOAPPart().getEnvelope();
        envelope.addNamespaceDeclaration("soap", "http://schemas.xmlsoap.org/soap/envelope/");
        envelope.setPrefix("soapenv");

        envelope.setAttribute("xmlns:tem", "http://tempuri.org/");

        headers = sm.getMimeHeaders();
        headers.addHeader("SOAPAction", "http://tempuri.org/IPublicChannelManagerService/RequestData");

        body = envelope.getBody();
        body.setPrefix("soapenv");

        requestData = body.addChildElement("RequestData");
        requestData.setPrefix("tem");

        requestDoc = requestData.addChildElement("requestDocument", "tem", "http://tempuri.org/");


     cdata = requestDoc.getOwnerDocument().createCDATASection("<Request>\n"
                + "           <Authentication CMId=\"6438\" Function=\"31\" Guid=\"5594FB83-F4D4-431F-B3C5-EA6D7ASDSBA795\" Password=\"y656g321TR\"/>\n"
                + "           <Establishment Id=\"297867\"/>\n"
                + "        </Request>");



        requestDoc.appendChild(cdata);

        System.out.println("----------------  SOAP Request ----------------------------");

        sm.writeTo(System.out);

        sfc = SOAPConnectionFactory.newInstance();
        connection = sfc.createConnection();
        requestUrl = new URL("http://pp.xxx.yyyy.co.uk/zzzz.svc?wsdl");

        response = connection.call(sm, requestUrl);

这很好用。我的问题是,有没有简单的方法,就像将对象传递给方法并创建SOAP请求一样 例如:就像JaxB一样,我会发送一个Bean,它会生成xml。

        outputStream = new ByteArrayOutputStream();

        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(beanObject, outputStream);

1 个答案:

答案 0 :(得分:1)

在发出请求之前,您应该拥有WSDL文件。然后使用例如生成您的特定类 wsimport 工具然后只需调用 JAX-WS webservice。您不必以这种方式自己构建请求

查看this教程。