如何从Java访问SOAP Web服务URL端点?
我一直在寻找一个具体的例子,我没有在哪里。不幸的是,在我正在研究的这个场景中,我使用REST的首选方法不可用,因此必须测试基于SOAP的方法。
设置是,例如,在www.website.com/soap.wsdl
处有一个SOAP WSDL文件。我正在尝试从CreateData端点发送和接收数据。
当我将WSDL文件添加到SoapUI软件中进行测试时,会生成以下SOAP消息模板;
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tic="{redacted}">
<soapenv:Header/>
<soapenv:Body>
<tic:CreateData>
<tic:request>{"testKey":"testValue"}</tic:request>
</tic:CreateData>
</soapenv:Body>
</soapenv:Envelope>
(我添加了测试JSON数据)
我似乎无法弄清楚如何将这个在SoapUI中正常工作的请求变成一个有效的测试Java代码。
当我将WSDL导入IDE时,它会生成一个类似于此的Java文件;
import javax.jws.WebService;
@WebService(serviceName = "{redacted}", portName = "{redacted}", endpointInterface = "{redacted}", targetNamespace = "{redacted}", wsdlLocation = "WEB-INF/wsdl/null/null.wsdl")
public class NewWebServiceFromWSDL {
public java.lang.String createData(java.lang.String request) {
//TODO implement this method
throw new UnsupportedOperationException("Not implemented yet.");
}
}
当然,我现在不知道接下来该做什么。如何在Java中创建SOAP信封?我希望看到为setSOAPEnvelopeHeader(),setSOAPEnvelopeBody(),setSOAPEnvelopeVariableRequest()等(或类似)等事物生成一些方法。
然后,一旦创建了SOAP Envelope对象(但是已经完成),那么我该如何实际发送消息并处理响应呢?
感到困惑......
答案 0 :(得分:0)
这是调用SOAP的残酷方式,但是它有效,并且很适合开始使用。然后,你做了一些修改来处理SOAPEnvelope / SOAPBody,这就是全部。
package xml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import com.sun.xml.internal.ws.encoding.soap.SOAP12Constants;
public class SOAPCall {
public static void main(String[] args) throws UnsupportedOperationException, SOAPException, IOException {
String endPoint = "URL";
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
String soapString = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tic=\"{redacted}\">"
+ "<soapenv:Header/><soapenv:Body>"
+ "<tic:CreateData><tic:request>{\"testKey\":\"testValue\"}</tic:request>"
+ "</tic:CreateData></soapenv:Body></soapenv:Envelope>";
InputStream is = new ByteArrayInputStream(soapString.getBytes());
SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);
MimeHeaders headers = request.getMimeHeaders();
// If SOAP Header is compulsory
// headers.addHeader("SOAPAction",
// "http://www.tdcare.com/DataInterchange");
headers.setHeader("Content-Type", "application/xml");
request.saveChanges();
SOAPMessage soapResponse = soapConnection.call(request, endPoint);
System.out.println(soapResponse);
}
}