WebService是一个应用非常广的技术,目前来说Axis、CXF、XFire等框架应接不暇,功能强大,但是JDK6自带的Jax-WS应用却较少,资料查起来也有点费劲。以下是使用JDK6自带的WebService写的一个查看QQ是否在线的简单应用
public class WSSoapClient {
/**
* 根据相关的参数,从配置文件里获取返回的消息
* @return
*/
public static SOAPMessage excuteRemind(){
MessageFactory msgFac = null;
SOAPConnectionFactory conFac = null;
SOAPMessage reply=null;
try {
msgFac=MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
conFac= SOAPConnectionFactory.newInstance();
/**
* 请求Message的过程
* 1、设置SOAP请求的参数
* 2、设置SOAP请求的头部信息
* 3、设置信封的命名空间等关信息
* 4、设置SOAP Body的信息(Body可以设置参数)
*/
SOAPMessage request=msgFac.createMessage();
//设置SOAP请求的基本参数
request.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8"); // 使用UTF-8编码SOAP消息
request.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); //
//设置SOAP请求头部信息
MimeHeaders mHers = request.getMimeHeaders();
mHers.setHeader("SOAPAction", "http://WebXml.com.cn/qqCheckOnline");// SOAPAction
mHers.setHeader("Host", "www.webxml.com.cn");
mHers.setHeader("Content-Type", "text/xml; charset=utf-8");
mHers.setHeader("Content-Length", "length");
SOAPEnvelope se=request.getSOAPPart().getEnvelope();
se.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi", null);
se.setAttributeNS("http://www.w3.org/2001/XMLSchema", "xsd", null);
se.setAttributeNS("http://schemas.xmlsoap.org/soap/envelope", "soap", null);
String methodName="qqCheckOnline";
SOAPBody body = request.getSOAPBody();
SOAPElement operation=body.addChildElement(methodName,null,"http://WebXml.com.cn/");
SOAPElement param = operation.addChildElement("qqCode");
param.addAttribute(new QName("type"), "xsd:string");
param.addTextNode("476763743");
SOAPConnection con=conFac.createConnection();
reply=con.call(request, "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx");
} catch (SOAPException e) {
e.printStackTrace();
}
return reply;
}
public static void main(String[]args){
SOAPMessage reply=WSSoapClient.excuteRemind();
try {
NodeList list=reply.getSOAPBody().getChildNodes();
Node result = (Node) list.item(0);
System.out.println(result.getTextContent());
} catch (SOAPException e) {
e.printStackTrace();
}
}
}