43

我对如何通过 java 向 web 服务发出请求有点困惑。

目前我唯一了解的是 webservices 使用 xml 结构化消息,但我仍然不太了解如何构造我的请求。

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getProductDetails xmlns="http://magazzino.example.com/ws">
      <productId>827635</productId>
    </getProductDetails>
  </soap:Body>
</soap:Envelope>

基本上我必须向 Web 服务发送 2 个参数,作为回报,我期望有另外两个参数。

我想有一些罐子可以完成大部分工作,但我没有在网上找到任何罐子。有人可以解释一下基础吗?

4

4 回答 4

100

SOAP 请求是一个 XML 文件,其中包含您要发送到服务器的参数。

SOAP 响应同样是一个 XML 文件,但现在包含了服务想要提供给您的所有内容。

基本上,WSDL 是一个 XML 文件,用于解释这两个 XML 的结构。


要在 Java 中实现简单的 SOAP 客户端,您可以使用 SAAJ 框架(它随 JSE 1.6 及更高版本提供):

SOAP with Attachments API for Java (SAAJ)主要用于直接处理在任何 Web 服务 API 中发生在幕后的 SOAP 请求/响应消息。它允许开发人员直接发送和接收肥皂消息,而不是使用 JAX-WS。

请参阅下面使用 SAAJ 的 SOAP Web 服务调用的工作示例(运行它!)。它调用这个网络服务

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

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

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}
于 2013-11-02T18:26:39.843 回答
8

当 WSDL 可用时,只需执行两个步骤即可调用该 Web 服务。

WSDL2Java第 1 步:从工具生成客户端源

第 2 步:使用以下命令调用操作:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

如果进一步观察,您会注意到Stub该类用于调用部署在远程位置的服务作为 Web 服务。调用它时,您的客户端实际上会生成 SOAP 请求并进行通信。同样,Web 服务将响应作为 SOAP 发送。借助 Wireshark 之类的工具,您可以查看交换的 SOAP 消息。

但是,由于您要求对基础知识进行更多解释,因此我建议您参考此处并使用其客户端编写一个 Web 服务以进一步了解它。

于 2013-11-02T18:24:03.010 回答
1

我在这里遇到了其他类似的问题。以上两个答案都是完美的,但这里试图为寻找SOAP1.1而不是SOAP1.2的人添加额外信息。

只需更改@acdcjunior 提供的一行代码,使用SOAPMessageFactory1_1Implimplementation,它将命名空间更改为 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/",即 SOAP1.1 实现。

callSoapWebService将方法第一行更改为以下。

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

我希望它对其他人有帮助。

于 2018-07-03T09:42:54.650 回答
0

如果您有 WSDL,您可以使用该 WSDL 文件在 SoapUI 中创建一个新的肥皂请求。
它将自动为输入请求生成结构/XML。

如果您有来自 SoapUI 的输入请求 xml,则可以使用以下 Java 代码的一些简单版本来调用 Soap 服务:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SimpleSoapClient {

public static void main(String args[]) throws IOException {
        
    String address="Hyderabad";

    /* place your xml request from soap ui below with necessary changes in parameters*/
    
    String xml="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://www.YourUrlAsPerWsdl.com/\">\r\n" + 
                 "   <soapenv:Header/>\r\n" + 
                 "   <soapenv:Body>\r\n" + 
                 "      <ws:callRest>\r\n" + 
                 "         <name>"+"Hello"+"</name>\r\n" + 
                 "         <address>"+address+"</address>\r\n" + 
                 "      </ws:callRest>\r\n" + 
                 "   </soapenv:Body>\r\n" + 
                 "</soapenv:Envelope>";
            String responseF=callSoapService(xml);
            System.out.println(responseF);
    }
    

}

static String callSoapService(String soapRequest) {
    try {
     String url = "https://gogle.com/service/hello"; // replace your URL here
     URL obj = new URL(url);
     HttpURLConnection con = (HttpURLConnection) obj.openConnection();
     
     // change these values as per soapui request on top left of request, click on RAW, you will find all the headers
     con.setRequestMethod("POST");
     con.setRequestProperty("Content-Type","text/xml; charset=utf-8"); 
     con.setDoOutput(true);
     DataOutputStream wr = new DataOutputStream(con.getOutputStream());
     wr.writeBytes(soapRequest);
     wr.flush();
     wr.close();
     String responseStatus = con.getResponseMessage();
     System.out.println(responseStatus);
     BufferedReader in = new BufferedReader(new InputStreamReader(
     con.getInputStream()));
     String inputLine;
     StringBuffer response = new StringBuffer();
     while ((inputLine = in.readLine()) != null) {
         response.append(inputLine);
     }
     in.close();
     
     // You can play with response which is available as string now:
     String finalvalue= response.toString();
     
     // or you can parse/substring the required tag from response as below based your response code
     finalvalue= finalvalue.substring(finalvalue.indexOf("<response>")+10,finalvalue.indexOf("</response>")); */
     
     return finalvalue;
     } 
    catch (Exception e) {
        return e.getMessage();
    }   
}

}

于 2021-06-24T16:24:09.280 回答