SOAP请求工具类
package xxx.util;
import javax.xml.namespace.QName;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPElement;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.Service.Mode;
import javax.xml.ws.soap.SOAPBinding;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import javax.activation.DataHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Node;
public class SoapSender {
private MessageFactory msgFactory;
private static SoapSender instance = new SoapSender();
private SoapSender(){
try {
//创建消息工厂
msgFactory = MessageFactory.newInstance();
} catch (SOAPException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static SoapSender getInstance() {
return instance;
}
public MessageFactory getMessageFactory() {
return msgFactory;
}
/* ******************* 以下是创建SOAPMessage*********************** */
/**
* 创建一个默认的SOAPMessage
* @return
*/
public SOAPMessage getMessage() throws SOAPException {
return msgFactory.createMessage();
}
/**
* 创建SOAPMessage
* @param params
* @return
*/
public SOAPMessage getMessage(Map<String, String> params) throws SOAPException, Exception {
// 创建消息对象
SOAPMessage message = msgFactory.createMessage();
// 获得一个SOAPPart对象
SOAPPart soapPart = message.getSOAPPart();
// 获得信封
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
// // 获得消息头
// SOAPHeader soapHeader = soapEnvelope.getHeader();
// // 添加头元素
// SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Fault", "soapenv","http://www.xxx.cn"));
// headerElement.addTextNode("JWS0229043");
// *****************创建soap消息主体*****************
SOAPBody soapBody = soapEnvelope.getBody();
// 添加消息主体
// Name bodyName = soapEnvelope.createName("INFO", "SOAP-ENV","http://www.xxx.cn");
Name bodyName = soapEnvelope.createName("INFO");
SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
Set<String> keys = params.keySet();
int i = 0;
for(String name:keys){
Name eleName = soapEnvelope.createName(name);
SOAPElement se = bodyElement.addChildElement(eleName);
// se.addChildElement("ServiceCode").addTextNode("10000061");
se.addTextNode(params.get(name));
i++;
}
// *************************************************
// // 添加SOAP附件
// URL url = new URL("http://xxx/1.jpg");
// DataHandler dataHandler = new DataHandler(url);//use the JAF
// message.addAttachmentPart(message.createAttachmentPart(dataHandler));
// 更新SOAP消息
message.saveChanges();
return message;
}
/**
* 创建SOAPMessage
* @param headers
* @param filePath:soap格式文件路径
* @return
*/
public SOAPMessage getMessage(MimeHeaders headers, String filePath) throws IOException, SOAPException {
// filePath = Thread.currentThread().getContextClassLoader().getResource("SOAPMessageResp.xml").getPath();
InputStream is = new FileInputStream(filePath);
SOAPMessage message = msgFactory.createMessage(headers, is);
is.close();
return message;
}
/* ******************* 以下是发送SOAP请求*********************** */
/**
* 发送SOAP请求
* @param requestUrl
* @param message
*/
public void send(String requestUrl,SOAPMessage message) throws SOAPException, IOException {
//创建SOAP连接
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection sc = scf.createConnection();
/*
* 实际的消息是使用 call()方法发送的,该方法接收消息本身和目的地作为参数,并返回第二个 SOAPMessage 作为响应。
* call方法的message对象为发送的soap报文,url为mule配置的inbound端口地址。
*/
URL urlEndpoint = new URL(requestUrl);
// 响应消息
SOAPMessage response = sc.call(message, urlEndpoint);
// *************************************************
if (response != null) {
//输出SOAP消息到控制台
System.out.println("Receive SOAP message:");
response.writeTo(System.out);
} else {
System.err.println("No response received from partner!");
}
// *************************************************
// 关闭连接
sc.close();
}
public void send1(String requestUrl,SOAPMessage message) throws SOAPException, Exception{
//创建SOAP连接
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection sc = scf.createConnection();
//发送SOAP消息到目的地,并返回一个消息
URL urlEndpoint = new URL(requestUrl);
SOAPMessage response = sc.call(message, urlEndpoint);
// *************************************************
response.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "utf-8");
// 打印服务端返回的soap报文供测试
System.out.println("Receive SOAP message:");
// 创建soap消息转换对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// 提取消息内容
Source sourceContent = response.getSOAPPart().getContent();
// Set the output for the transformation
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
// *************************************************
// 关闭连接
sc.close();
// *************************************************
/* 模拟客户端A,异常处理测试*/
SOAPBody ycBody = response.getSOAPBody();
Node ycResp = ycBody.getFirstChild();
System.out.print("returnValue:"+ycResp.getTextContent());
}
/**
* 发送SOAP请求
public void send1(String requestUrl,SOAPMessage request) {
//定义serviceName对应的QName,第一个参数是对应的namespace
QName serviceName = new QName("http://xxx.com/", "SOAPMessageService");
//定义portName对应的QName
QName portName = new QName("http://xxx.com/", "SOAPMessagePort");
//使用serviceName创建一个Service对象,该对象还不能直接跟WebService对象进行交互
Service service = Service.create(serviceName);
// //指定wsdl文件的位置
// URL wsdl = new URL("http://localhost:8080/test/jaxws/services/SOAPMessage?wsdl");
// Service service = Service.create(wsdl, serviceName);
//创建一个port,并指定WebService的地址,指定地址后我们就可以创建Dispatch了。
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, requestUrl);
//创建一个Dispatch对象
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Mode.MESSAGE);
//调用Dispatch的invoke方法,发送一个SOAPMessage请求,并返回一个SOAPMessage响应。
SOAPMessage response = dispatch.invoke(request);
System.out.println("服务端返回如下: ");
try {
response.writeTo(System.out);
} catch (Exception e) {}
}
*/
}
测试方法
public static void main(String[] args) throws SOAPException, Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("a","1");
String string="http://xxx/xxx";
/** *************以下是SOAP请求***************** */
SoapSender sender = SoapSender.getInstance();
SOAPMessage message = sender.getMessage();
// SOAPMessage message = sender.getMessage(params);
// SOAPMessage message = sender.getMessage(null,"D:\SOAPMessageResp.xml");
message.writeTo(System.out);
sender.send(string,message);
}
/*******************************************************************************************/
服务端:
package server;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import org.w3c.dom.Node;
import javax.xml.messaging.JAXMServlet;
import javax.xml.messaging.ReqRespListener;
public class ServerAction extends JAXMServlet implements ReqRespListener {
static MessageFactory mf = null;
// 创建一个消息工厂
static {
try {
mf = MessageFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
};
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
}
// 处理传过来的SOAP消息,并返回一个SOAP消息
public SOAPMessage onMessage(SOAPMessage msg) {
SOAPMessage resp = null;
try {
System.out.println("传入的消息:");
msg.writeTo(new FileOutputStream(new File("../webapps/soapmessage.xml")));
SOAPBody ycBody = msg.getSOAPBody();
Node ycResp = ycBody.getFirstChild();
System.out.println("returnValue:"+ycResp.getTextContent());
// 创建一个返回消息
resp = mf.createMessage();
SOAPEnvelope se = resp.getSOAPPart().getEnvelope();
se.getBody().addChildElement(se.createName("ResponseMessage")).addTextNode("Received Message,Thanks");
return resp;
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}
}
配置web.xml
<servlet> <servlet-name>StudentInfoServlet</servlet-name> <servlet-class>server.ServerAction</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>StudentInfoServlet</servlet-name> <url-pattern>/StudentInfoServlet</url-pattern> </servlet-mapping>