现在的位置: 首页 > 综合 > 正文

C#调用Java jaxws开发的webservice服务

2014年10月20日 ⁄ 综合 ⁄ 共 19245字 ⁄ 字号 评论关闭

                     C#调用Java jaxws开发的webservice服务

1、jaxws是基于wsdl国际标准基于xml传输协议,数据交互都基于标准xml格式,如果格式不正确交互会失败;关于jaxws整合spring并增加访问权限口令验证这里不再说明。

2、这里讲述开发注意事项、口令验证、数据加密(暂未涉及)、java服务端与C#客户的权限验证和数据交互;

3、C#如何调用java jaxws开发webservice服务呢?

参考文档:http://www.cnblogs.com/iamlilinfeng/archive/2012/09/25/2700049.html

在C#中新建WCF项目,并新建WCF测试webservice【WCF是基于标准wsdl协议】,如果通过WCF协议测试通过后,表示C#和java交互正常【测试之前关闭java saohandler验证】;WCF链接webservice只是做测试还没涉及安全验证

4、java服务端加入soaphandle验证,c#发送口令和消息,以下是C#客户端关键代码:

C#新建文件:

MySoapClient.cs 负责发送数据:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml;
using System.Runtime.InteropServices;
using System.Configuration;

/// <summary>
/// 重新实现soap客户端
/// </summary>
public class MySoapClient
{

    private System.Net.HttpWebRequest m_Client = null;
    private string xmlTemplate = string.Empty;
    private XmlDocument m_Dom = new XmlDocument();


    /// <summary>
    /// 用户名及密码
    /// </summary>
    public static string UserName = "TOKEpcinf&Amdocs123";//用户名及密码【在服务端将获取到该属性,验证用户口令】


    /// <summary>
    /// webservice地址
    /// </summary>
    public static string RequestUrl = @"http://192.168.2.106:9090/slhb2.0/AngleService?wsdl";

    private static string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
 + " <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" >"
 + "    <soapenv:Header>"
 + "       <ns1:username soapenv:actor=\"http://schemas.xmlsoap.org/soap/actor/next\" soapenv:mustUnderstand=\"0\"  xmlns:ns1=\"Authorization\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">TOKEpcinf</ns1:username>"
 + "       <ns2:password soapenv:actor=\"http://schemas.xmlsoap.org/soap/actor/next\" soapenv:mustUnderstand=\"0\"  xmlns:ns2=\"Authorization\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">Amdocs123</ns2:password>"
 + "    </soapenv:Header>"
 + "    <soapenv:Body  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
 + "       <{0} xmlns='http://jaxws.webservice.mapscience.com/'>"
 + "  <arg0 xmlns=''>hiloAngle123</arg0>" //这里参数标签必须是[arg0,arg1,arg.....],否则服务端接收不了值
 + "       </{0}>"
 + "    </soapenv:Body>"
 + " </soapenv:Envelope>";
 
    /// <summary>
    /// 默认构造函数
    /// </summary>
    public MySoapClient(string methodName)
    {
        m_Dom.LoadXml(string.Format(xml, methodName));
        m_Client = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(RequestUrl);
        m_Client.Method = "POST";
        m_Client.Headers["SOAPAction"] = @"""""";               //双引号
        m_Client.ContentType = "text/xml; charset=utf-8";
        m_Client.Accept = "application/dime, multipart/related, text/*,application/soap+xml";
        m_Client.UserAgent = "Jaxws/2.0";
        m_Client.Headers["Cache-Control"] = "no-cache";
        m_Client.Headers["Pragma"] = "no-cache";
    }
    ///// <summary>
    ///// 默认构造函数
    ///// </summary>
    //public MySoapClient(string path)
    //{
    //    m_Dom.LoadXml(xml);
    //    m_Client = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(path);
    //    m_Client.Method = "POST";
    //    m_Client.Headers["SOAPAction"] = @"""""";               //双引号
    //    m_Client.ContentType = "text/xml; charset=utf-8";
    //    m_Client.Accept = "application/dime, multipart/related, text/*,application/soap+xml";
    //    m_Client.UserAgent = "Axis/1.4";
    //    m_Client.Headers["Cache-Control"] = "no-cache";
    //    m_Client.Headers["Pragma"] = "no-cache";
    //}

    /// <summary>
    /// 发送webservice请求
    /// </summary>
    /// <param name="path">webservice地址</param>
    /// <param name="functionname">函数名称</param>
    /// <param name="xml">xml报文</param>
    /// <returns></returns>
    public string SendRequest(string xml)
    {
        try
        {
            //加入用户名及密码
            XmlNode header = m_Dom.ChildNodes[1].ChildNodes[0];         
            XmlNode body = m_Dom.ChildNodes[1].ChildNodes[1];
            header.ChildNodes[0].InnerText = UserName;
            header.ChildNodes[1].InnerText = "";
            body.ChildNodes[0].ChildNodes[0].InnerText = xml;
            string sendXml = m_Dom.OuterXml;           
            Console.WriteLine(" XML报文==   " + sendXml);
            return send(sendXml);
        }
        catch (Exception ex)
        {
            return "加入用户名及密码 异常: " + ex.Message;
        }
    }

    private string send(string data)
    {
        try
        {
            //【发送】
            m_Client.ContentLength =  data.Length;
            System.IO.Stream sendStread = m_Client.GetRequestStream();
            byte[] sendData = new ASCIIEncoding().GetBytes(data);
            sendStread.Write(sendData, 0, sendData.Length);
            sendStread.Close();
            //【接收】
            System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)m_Client.GetResponse();
            System.IO.StreamReader reader = new System.IO.StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();

            XmlDocument xd = new XmlDocument();
            xd.LoadXml(content);
            return xd.DocumentElement.InnerText;
   
        }
        catch (System.Net.WebException exp)
        {
            System.Net.WebResponse wr = exp.Response;
            System.IO.StreamReader esr = new System.IO.StreamReader(wr.GetResponseStream(), Encoding.UTF8);
            string Error = esr.ReadToEnd();
            esr.Close();
            return "不可预知异常: " + Error + ",系统:" + exp.Message;
        }
    }
  
}

新建GET.cs 负责拼接发送的参数:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;

namespace WindowsXML
{
    internal class GET
    {
        private static XmlDocument NewXml()
        {
            XmlDocument xmlBack = new XmlDocument();
            xmlBack.AppendChild(xmlBack.CreateXmlDeclaration("1.0", "UTF-8", null));
            xmlBack.AppendChild(xmlBack.CreateElement("DBSET"));
            XMLHelper.AddNewNode(xmlBack, "DBSET", "R", "C", "", "");
            return xmlBack;
        }

        public static bool CheckDataTable(List<string[]> tab)
        {
            try
            {
                if (tab != null && tab.Count > 0)
                {
                    string str = "";
                    for (int i = 0; i < tab.Count; i++)
                    {
                        str += tab[i].ToString();
                    }
                    return str.Length > 0;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public static bool CheckDataTable(DataTable tab)
        {
            try
            {
                if (tab != null && tab.Rows.Count > 0)
                {
                    string str = "";
                    for (int i = 0; i < tab.Columns.Count; i++)
                    {
                        str += tab.Rows[0][i].ToString();
                    }
                    return str.Length > 0;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool CheckReMsg(string str)
        {
            if (str != null && str.IndexOf("不可预知异常") == -1)
            {
                XmlDocument xdoc = new XmlDocument();
                try
                {
                    xdoc.LoadXml(str);
                    //if (xdoc.DocumentElement.Attributes[0].Name != "RESULT")
                    //{
                    //    return false;
                    //}
                    //else 
                    if (xdoc.DocumentElement.Attributes[0].Value == "0")
                    {
                        return true;
                    }
                    else if (xdoc.DocumentElement.Attributes[0].Value == "1")
                    {
                        XmlNode no = xdoc.DocumentElement.ChildNodes[0];
                        for (int i = 0; i < no.ChildNodes.Count; i++)
                        {
                            if (no.ChildNodes[i].Attributes[0].Value.Equals("RETURN_FLAG") && no.ChildNodes[i].InnerText.Equals("0"))
                            {
                                return true;
                            }
                        }
                        return false;
                    }
                }
                catch (Exception)
                {
                    return false;
                }
            }

            return false;
        }


        public static string ZuCan(string[] strnames, string[] strparms)
        {
            StringBuilder strtitle = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><DBSET>");

            string strrow = "<C N=\"{0}\">{1}</C>";

            strtitle.Append("<R>");

            for (int j = 0; strparms != null && j < strnames.Length; j++)
            {
                strtitle.Append(string.Format(strrow, strnames[j], strparms[j]));
            }
            strtitle.Append("</R>");

            strtitle.Append("</DBSET>");

            return strtitle.ToString();
        }

        public static string ZuCan(string[] strs, DataTable dt)
        {
            StringBuilder strtitle = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><DBSET>");
            string strrow = "<C N=\"{0}\">{1}</C>";

            for (int i = 0; dt != null && i < dt.Rows.Count; i++)
            {
                strtitle.Append("<R>");
                for (int j = 0; j < strs.Length; j++)
                {
                    strtitle.Append(string.Format(strrow, strs[j], dt.Rows[i][strs[j]] == null ? "" : dt.Rows[i][strs[j]].ToString()));
                }
                strtitle.Append("</R>");
            }
            strtitle.Append("</DBSET>");

            return strtitle.ToString();
        }

        public static string ZuCan(string[] strs, List<string[]> listparms)
        {
            StringBuilder strtitle = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><DBSET>");
            string strrow = "<C N=\"{0}\">{1}</C>";

            for (int i = 0; listparms != null && i < listparms.Count; i++)
            {
                strtitle.Append("<R>");
                for (int j = 0; j < strs.Length; j++)
                {
                    strtitle.Append(string.Format(strrow, strs[j], listparms[i][j].ToString()));
                }
                strtitle.Append("</R>");
            }
            strtitle.Append("</DBSET>");

            return strtitle.ToString();
        }
    }
}

新建XMLHelper.cs 负责拼接xml:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace WindowsXML
{
    public class XMLHelper
    {
        /// <summary>
        /// XML格式返回
        /// </summary>
        /// <param name="xmlPara">xml</param>
        /// <returns></returns>
        public static XmlDocument LoadXmlFormatResult(string xmlPara)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlPara);
            return xmlDoc;
        }
        /// <summary>
        /// 通过节点名称获取节点集合
        /// </summary>
        /// <param name="xmlDoc">XML格式文档</param>
        /// <param name="Name">节点名称</param>
        /// <returns></returns>
        public static List<XmlNode> GetXmlNodesByName(XmlDocument xmlDoc, string name)
        {
            List<XmlNode> xmlNode = new List<XmlNode>();
            if (xmlDoc == null)
            {
                return xmlNode;
            }
            if (xmlDoc.DocumentElement.Name.ToString().ToLower() == name.ToLower())
            {
                xmlNode.Add((XmlNode)xmlDoc.DocumentElement);
            }
            XmlNodeList xmlNodeList = xmlDoc.DocumentElement.ChildNodes;
            foreach (XmlNode xn in xmlNodeList)
            {
                GetNodesByName(xmlNode, xn, name);
            }
            return xmlNode;
        }

        public static XmlDocument BaseXML(string filename)
        {
            if (filename == null && filename == "")
            {
                filename = "Config.xml";
            }
            XmlDocument xdoc = new XmlDocument();
            if (System.IO.File.Exists(filename))
            {
                try
                {
                    xdoc.Load(filename);
                    return xdoc;
                }
                catch (Exception)
                {
                    System.IO.File.Copy(filename, filename + ".非法的XML文件");
                    System.IO.File.Delete(filename);
                }
            }

            xdoc.AppendChild(xdoc.CreateXmlDeclaration("1.0", "UTF-8", null));
            xdoc.AppendChild(xdoc.CreateElement("DBSET"));

            xdoc.DocumentElement.AppendChild(xdoc.CreateNode(XmlNodeType.Element, "R", null));
            return xdoc;
        }

        /// <summary>通过 节点名称 获取 节点
        /// </summary>
        /// <param name="name">节点名称</param>
        /// <returns></returns>
        public static List<XmlNode> GetNodesByName(XmlDocument xdoc, string name)
        {
            List<XmlNode> list = new List<XmlNode>();
            if (xdoc == null)
            {
                return list;
            }

            if (xdoc.DocumentElement.Name.ToString().ToLower() == name.ToLower())
                list.Add((XmlNode)xdoc.DocumentElement);

            XmlNodeList nlst = xdoc.DocumentElement.ChildNodes;
            foreach (XmlNode xns in nlst)
            {
                GetNodesByName(list, xns, name);
            }
            return list;
        }
        public static void GetNodesByName(List<XmlNode> list, XmlNode node, string name)
        {
            if (node.Name.ToString().ToUpper() == name.ToUpper())
            {
                list.Add(node);
            }
            foreach (XmlNode xns in node.ChildNodes)
            {
                GetNodesByName(list, xns, name);
            }
        }

        /// <summary>通过 节点属性值获取 节点
        /// </summary>
        /// <param name="name">属性值</param>
        /// <returns></returns>
        public static List<XmlNode> GetNodeByAttribute(XmlDocument xdoc, string name)
        {
            List<XmlNode> list = new List<XmlNode>();
            if (xdoc == null)
            {
                return list;
            }

            for (int i = 0; xdoc.DocumentElement.Attributes != null && i < xdoc.DocumentElement.Attributes.Count; i++)
            {
                if (xdoc.DocumentElement.Attributes[i].Value.ToString().ToLower() == name.ToLower())
                    list.Add((XmlNode)xdoc.DocumentElement);
            }
            foreach (XmlNode xns in xdoc.DocumentElement.ChildNodes)
            {
                GetNodeByAttribute(list, xns, name);
            }
            return list;
        }
        public static void GetNodeByAttribute(List<XmlNode> list, XmlNode node, string name)
        {
            for (int i = 0; node.Attributes != null && i < node.Attributes.Count; i++)
            {
                if (node.Attributes[i].Value.ToString().ToLower() == name.ToLower())
                    list.Add(node);
            }
            foreach (XmlNode xns in node.ChildNodes)
            {
                GetNodeByAttribute(list, xns, name);
            }
        }

        public static void AddNode(XmlNode nodeParent, XmlNode newChild, string pn)
        {
            if (nodeParent.Name == pn)
            {
                nodeParent.AppendChild(newChild.Clone());
            }
            foreach (XmlNode xns in nodeParent.ChildNodes)
            {
                AddNode(xns, newChild, pn);
            }
        }
        public static void AddNode(XmlNode nodeParent, XmlNode newChild)
        {
            if (nodeParent == null || newChild == null)
            {
                return;
            }
            nodeParent.AppendChild(newChild);
        }
        /// <summary>添加新的节点,不理会是否有重复
        /// </summary>
        /// <param name="Pname">父节点名称 R</param>
        /// <param name="Cname">要添加的节点的名称 P</param>
        /// <param name="Aname">属性名 N </param>
        /// <param name="attvalue">属性值</param>
        /// <param name="innertext">节点值</param>
        /// <returns></returns>
        public static void AddNewNode(XmlDocument xdoc, string Pname, string Cname, string Aname, string attvalue, string innertext)
        {
            XmlNode newNode = xdoc.CreateNode(XmlNodeType.Element, Cname, null);
            if (innertext != null)
            {
                newNode.InnerText = innertext;
            }

            if (attvalue != null && attvalue != "")
            {
                XmlNode newAtt = xdoc.CreateNode(XmlNodeType.Attribute, Aname, null);
                newAtt.Value = attvalue;

                newNode.Attributes.SetNamedItem(newAtt);
            }
            if (xdoc.DocumentElement.Name == Pname)
            {
                xdoc.DocumentElement.AppendChild(newNode.Clone());
            }

            XmlNodeList nlst = xdoc.DocumentElement.ChildNodes;
            foreach (XmlNode xns in nlst)
            {
                AddNode(xns, newNode, Pname);
            }
        }

        /// <summary>修改节点
        /// </summary>
        /// <param name="Cname">节点名称</param>
        /// <param name="Aname">要修改的属性</param>
        /// <param name="attvalue">新的属性值</param>
        /// <param name="innertext">新的节点值</param>
        public static void UpdateNode(XmlDocument xdoc, string Cname, string Aname, string attvalue, string innertext)
        {
            List<XmlNode> list = GetNodesByName(xdoc, Cname);
            if (list != null && list.Count > 0)
            {
                foreach (XmlNode node in list)
                {
                    node.InnerText = innertext;
                    if (node.Attributes[Aname] == null)
                    {
                        XmlNode newAtt = xdoc.CreateNode(XmlNodeType.Attribute, Aname, null);
                        newAtt.Value = attvalue;

                        node.Attributes.SetNamedItem(newAtt);
                    }
                    else
                    {
                        node.Attributes[Aname].Value = attvalue;
                    }
                }
            }
        }
        /// <summary>修改节点
        /// </summary>
        /// <param name="node">要修改的节点</param>
        /// <param name="Aname">要修改的属性</param>
        /// <param name="attvalue">新的属性值</param>
        /// <param name="innertext">新的节点值</param>
        public static void UpdateNode(XmlDocument xdoc, XmlNode node, string Aname, string attvalue, string innertext)
        {
            node.InnerText = innertext;
            if (node.Attributes[Aname] == null)
            {
                XmlNode newAtt = xdoc.CreateNode(XmlNodeType.Attribute, Aname, null);
                newAtt.Value = attvalue;

                node.Attributes.SetNamedItem(newAtt);
            }
            else
            {
                node.Attributes[Aname].Value = attvalue;
            }
        }

        /// <summary>修改或添加节点
        /// </summary>
        /// <param name="Pname">父节点名称 R</param>
        /// <param name="Cname">要添加的节点的名称 P</param>
        /// <param name="Aname">属性名 N </param>
        /// <param name="attvalue">属性值</param>
        /// <param name="innertext">节点值</param>
        /// <returns></returns>
        public static void UpOrAddNode(XmlDocument xdoc, string Pname, string Cname, string Aname, string attvalue, string innertext)
        {
            List<XmlNode> list = GetNodesByName(xdoc, Cname);
            if (list != null && list.Count > 0)
            {
                foreach (XmlNode node in list)
                {
                    node.InnerText = innertext;
                    if (node.Attributes[Aname] == null)
                    {
                        XmlNode newAtt = xdoc.CreateNode(XmlNodeType.Attribute, Aname, null);
                        newAtt.Value = attvalue;

                        node.Attributes.SetNamedItem(newAtt);
                    }
                    else
                    {
                        node.Attributes[Aname].Value = attvalue;
                    }
                }
            }
            else
            {
                XmlNode newNode = xdoc.CreateNode(XmlNodeType.Element, Cname, null);
                newNode.InnerText = innertext;
                if (attvalue != null && attvalue != "")
                {
                    XmlNode newAtt = xdoc.CreateNode(XmlNodeType.Attribute, Aname, null);
                    newAtt.Value = attvalue;

                    newNode.Attributes.SetNamedItem(newAtt);
                }
                if (xdoc.DocumentElement.Name == Pname)
                {
                    xdoc.DocumentElement.AppendChild(newNode.Clone());
                }

                XmlNodeList nlst = xdoc.DocumentElement.ChildNodes;
                foreach (XmlNode xns in nlst)
                {
                    AddNode(xns, newNode, Pname);
                }
            }
        }
        /// <summary>删除节点
        /// </summary>
        /// <param name="node"></param>
        public static void DelNode(XmlDocument xdoc, XmlNode node)
        {
            node.ParentNode.RemoveChild(node);
        }

        #region 去重
        public static void QuChong(XmlDocument xdoc)
        {
            QuChongByNode((XmlNode)xdoc.DocumentElement);
        }

        public static void QuChong(XmlDocument xdoc, string nodename)
        {
            List<XmlNode> list = GetNodesByName(xdoc, nodename);
            if (list != null)
            {
                foreach (XmlNode node in list)
                {
                    QuChongByNode(node);
                }
            }
        }

        private static void QuChongByNode(XmlNode node)
        {
            foreach (XmlNode cn in node.ChildNodes)
            {
                QuChongByNode(cn);
            }

            for (int i = 1; node.ChildNodes.Count > 1 && i < node.LastChild.ParentNode.ChildNodes.Count; i++)
            {
                if (node.LastChild.ParentNode.ChildNodes[i].InnerXml.Equals(node.FirstChild.InnerXml))
                {
                    node.LastChild.ParentNode.RemoveChild(node.LastChild);
                    i = -1;
                }
            }
        }
        #endregion

        ////<summary>保存新的XML文件
        ////</summary>
        ////<param name="fileName">文件路径</param>
        ////<returns></returns>
        public static bool Save(XmlDocument xdoc, string fileName)
        {
            try
            {
                if (fileName != null && fileName.Length > 4)
                {
                    xdoc.Save(fileName);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

C#测试代码,改代码向java服务端发送handler验证和数据,服务端并返回接口:

//安全认证
        private void button4_Click(object sender, EventArgs e)
        {
        //    string[] value = { "1210128117200033090203", "1201" };
        //    string[] name = { "Jaxw安全认证", "area" };
         //   string param = WindowsXML.GET.ZuCan(value, name);
         //   Console.WriteLine(param);
            MySoapClient my = new MySoapClient("angels");//angels是java的方法名
            anglelabel.Text = my.SendRequest("12323") + "\r\n";
            //anglelabel.Text = my.SendRequest(param) + "\r\n";

Console.WriteLine(anglelabel.Text); }



5、java jaxwshandle验证代码:

package com.mapscience.webservice.jaxws.handler;

import java.util.Set;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;

/**
 * <p>
 * Title: spring整合jaxws基于handler请求验证
 * </p>
 * <p>
 * Description:当用户通过ws请求时,将会被本类进行拦截,并进行验证,只有合法用户才能访问
 * </p>
 * <p>
 * Copyright: Copyright (c) 2014
 * </p>
 * <p>
 * Company: 
 * </p>
 * 
 * @author 2014-1-1
 * @version 1.0
 * @Excample 【网上说在chain-handler.xml配置文件中配置拦截,但这个方式没成功】采样另一方式,在spring中配置: <bean
 *           id="myHandler"
 *           class="com.mapscience.webservice.jaxws.handler.TKHandler" />
 *           <servlet:binding url="/AngleService" > <servlet:service >
 *           <core:service bean="#baseJaxws"> <core:handlers> <ref
 *           bean="myHandler"/> </core:handlers> </core:service>
 *           </servlet:service> </servlet:binding>
 * 
 * 
 */
public class TKHandler implements SOAPHandler<SOAPMessageContext> {
	public boolean handleMessage(SOAPMessageContext context) {

		System.out.println("请求被拦截.");

		Boolean outbound = (Boolean) context
				.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		if (!outbound.booleanValue()) {
			SOAPMessage soapMessage = context.getMessage();
			try {
				SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
				SOAPHeader soapHeader = soapEnvelope.getHeader();
				System.out.println(soapHeader.getFirstChild());
				if (soapHeader == null) {
					generateSoapFault(soapMessage, "No Message Header...");
				}
				Iterator it = soapHeader
						.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT);
				if (it == null || !it.hasNext()) {
					generateSoapFault(soapMessage,
							"No Header block for role next");
				}
				Node node = (Node) it.next();
				String value = node == null ? null : node.getValue();
				
				if (value == null) {
					generateSoapFault(soapMessage,
							"No authation info in header blocks");
				}
				String[] infos = value.split("&");
				return authValidate(infos[0], infos[1]);

			} catch (SOAPException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	private boolean authValidate(String userName, String password) {
		if (userName == null || password == null) {
			return false;
		}

		if ("admin".equals(userName) && "admin".equals(password)) {
			return true;
		}
		return false;
	}

	private void generateSoapFault(SOAPMessage soapMessage, String reasion) {
		try {
			SOAPBody soapBody = soapMessage.getSOAPBody();
			SOAPFault soapFault = soapBody.getFault();

			if (soapFault == null) {
				soapFault = soapBody.addFault();
			}

			soapFault.setFaultString(reasion);

			throw new SOAPFaultException(soapFault);

		} catch (SOAPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean handleFault(SOAPMessageContext context) {

		System.out.println("Server : handleFault()......");

		return true;
	}

	public void close(MessageContext context) {
		System.out.println("服务验证机制关闭.");
	}

	public Set<QName> getHeaders() {
		System.out.println("服务验证机制初始化.");
		return null;
	}

	private void generateSOAPErrMessage(SOAPMessage msg, String reason) {
		try {
			SOAPBody soapBody = msg.getSOAPPart().getEnvelope().getBody();
			SOAPFault soapFault = soapBody.addFault();
			soapFault.setFaultString(reason);
			throw new SOAPFaultException(soapFault);
		} catch (SOAPException e) {
		}
	}

}

6、java webservice访问层:

@WebService
public class AngleJaxws {
@WebMethod
	public String angels(String v) {
	
		return "服务器返回结果" + v+"->"+map;
	}
}

7、记住jaxws是基于wsdl国际标准xml数据传输,支持任何语言平台,发送的xml永远是如下格式,如果格式出错将接收不了数据:


    private static string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
 + " <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" >"
 + "    <soapenv:Header>"
 + "       <ns1:username soapenv:actor=\"http://schemas.xmlsoap.org/soap/actor/next\" soapenv:mustUnderstand=\"0\"  xmlns:ns1=\"Authorization\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">TOKEpcinf</ns1:username>"
 + "       <ns2:password soapenv:actor=\"http://schemas.xmlsoap.org/soap/actor/next\" soapenv:mustUnderstand=\"0\"  xmlns:ns2=\"Authorization\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">Amdocs123</ns2:password>"
 + "    </soapenv:Header>"
 + "    <soapenv:Body  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
 + "       <angles xmlns='http://jaxws.webservice.mapscience.com/'>"  //angles是服务端的方法名称
 + "  <arg0 xmlns=''>hiloAngle123</arg0>"  //arg是方法参数【标签必须是arg0/arg1/arg2/arg....】,否则服务端接收参数为Null
 + "       </angles>"
 + "    </soapenv:Body>"
 + " </soapenv:Envelope>";



抱歉!评论已关闭.