如何从Java类调用SOAP Web服务?
我对webservices的世界相对来说比较陌生,我的研究似乎让我困惑,而不是启发我,我的问题是我得到了一个库(jar),我必须用一些webservices功能来扩展它 这个库将被其他开发人员共享,jar中的类将是具有调用webservice的方法的类(该方法基本上设置类的属性,执行一些业务逻辑,如将对象存储在db中等,并通过这些修改发回对象)。我希望对该服务的调用尽可能简单,希望尽可能简单,以便使用该类的开发人员只需执行以下操作如何从Java类调用SOAP Web服务?,java,web-services,soap,jax-ws,saaj,Java,Web Services,Soap,Jax Ws,Saaj,我对webservices的世界相对来说比较陌生,我的研究似乎让我困惑,而不是启发我,我的问题是我得到了一个库(jar),我必须用一些webservices功能来扩展它 这个库将被其他开发人员共享,jar中的类将是具有调用webservice的方法的类(该方法基本上设置类的属性,执行一些业务逻辑,如将对象存储在db中等,并通过这些修改发回对象)。我希望对该服务的调用尽可能简单,希望尽可能简单,以便使用该类的开发人员只需执行以下操作 Car c = new Car("Blue"); c.webme
Car c = new Car("Blue");
c.webmethod();
我一直在研究服务器上使用的JAX-WS,但在我看来,我不需要在服务器上创建
wsimport
,也不需要在客户端创建wsimport
,因为我知道两者都有类,所以我只需要在服务器和客户端中共享的类之间进行一些交互。您认为在类中执行web服务和调用有何意义?我理解您的问题归结为如何从Java调用SOAP(JAX-WS)web服务并获取其返回对象。在这种情况下,有两种可能的方法:
wsimport
生成Java类并使用;或关于第一种方法(使用
wsimport
):
我看到您已经有了服务(实体或其他)业务类,wsimport
生成了一组全新的类(以某种方式与您已有的类重复)
不过,在这种情况下,恐怕您只能:
- 调整(编辑)wsimport生成的代码,使其使用您的业务类(这很难,而且不值得——记住每次WSDL更改时,您都必须重新生成并重新适应代码);或
- 放弃并使用
生成的类。(在此解决方案中,业务代码可以“使用”生成的类作为来自另一个体系结构层的服务。)wsimport
- 使用SAAJ(SOAP with Attachments API for Java)框架(见下文,它与JavaSE1.6或更高版本一起提供)进行调用;或
- 您还可以通过
(以及一些java.net.HttpUrlconnection
处理)来实现java.io
- 使用诸如JAXB之类的OXM(对象到XML映射)框架将XML从对象序列化/反序列化到对象中
- 或者,如果必须,手动创建/解析XML(如果接收到的对象与发送的对象只有一点点不同,那么这可能是最好的解决方案)
java.net.HttpUrlConnection
创建SOAP客户机并不难(但也不是那么简单),您可以在一个非常好的开始代码中找到它
我建议您使用SAAJ框架:
SOAP with Attachments API for Java(SAAJ)主要用于直接处理任何Web服务API中幕后发生的SOAP请求/响应消息。它允许开发人员直接发送和接收soap消息,而不是使用JAX-WS
下面是一个使用SAAJ的SOAP web服务调用的工作示例(运行它!)。它叫
import javax.xml.soap.*;
公共类SOAPClientSAAJ{
//SAAJ-SOAP客户端测试
公共静态void main(字符串参数[]){
/*
下面的示例显示了来自以下位置的Web服务的请求:
https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
要调用其他WS,请更改以下参数:
-SOAP端点URL(即服务响应的来源)
-肥皂剧
还要更改此类中方法createSoapEnvelope()的内容
实际发送的SOAP信封的内部部分。
*/
字符串soapEndpointUrl=”https://www.w3schools.com/xml/tempconvert.asmx";
字符串soapAction=”https://www.w3schools.com/xml/CelsiusToFahrenheit";
callSoapWebService(soapEndpointUrl、soapAction);
}
私有静态void createSoapEnvelope(SOAPMessage SOAPMessage)引发SOAPException{
SOAPPart SOAPPart=soapMessage.getSOAPPart();
字符串myNamespace=“myNamespace”;
字符串myNamespaceURI=”https://www.w3schools.com/xml/";
//肥皂袋
SOAPEnvelope=soapPart.getEnvelope();
addNamespaceDeclaration(myNamespace,myNamespaceURI);
/*
构造的SOAP请求消息:
100
*/
//皂体
SOAPBody SOAPBody=envelope.getBody();
SOAPElement-soapBodyElem=soapBody.addChildElement(“CelsiusToFahrenheit”,myNamespace);
SOAPElement soapBodyElem1=soapBodyElem.addChildElement(“摄氏度”,myNamespace);
soapBodyElem1.addTextNode(“100”);
}
私有静态void callSoapWebService(字符串soapEndpointUrl,字符串soapAction){
试一试{
//创建SOAP连接
SOAPConnectionFactory SOAPConnectionFactory=SOAPConnectionFactory.newInstance();
SOAPConnection-SOAPConnection=soapConnectionFactory.createConnection();
//
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:
https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
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 = "https://www.w3schools.com/xml/tempconvert.asmx";
String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "https://www.w3schools.com/xml/";
// 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="https://www.w3schools.com/xml/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:CelsiusToFahrenheit>
<myNamespace:Celsius>100</myNamespace:Celsius>
</myNamespace:CelsiusToFahrenheit>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
soapBodyElem1.addTextNode("100");
}
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;
}
}
$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl
DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private int age;
private String address; //setter and getters below
}
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Slf4j
public class SoapGenerator {
protected static final ObjectMapper XML_MAPPER = new XmlMapper()
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule());
private static final String SOAP_BODY_OPEN = "<soap:Body>";
private static final String SOAP_BODY_CLOSE = "</soap:Body>";
private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";
public static String soapWrap(String xml) {
return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
}
public static String soapUnwrap(String xml) {
return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
}
}
public static void main(String[] args) throws Exception{
Person p = new Person();
p.setName("Test");
p.setAge(12);
String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
log.info("Generated String");
log.info(xml);
}