WCF自托管服务

一般有两种方式实现:

1、通过代码设置直接实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using WcfTest;

namespace WcfHosting
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof (SoapService)))
            {
                host.AddServiceEndpoint(typeof(ISoapService), new WSHttpBinding(), "http://127.0.0.1:1234/neohope");

                if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri("http://127.0.0.1:9999/neohope/metadata");
                    host.Description.Behaviors.Add(behavior);
                }

                host.Opened += delegate
                {
                    Console.WriteLine("service started, press enter to exit.");
                };
                host.Open();
                Console.Read();
            }
        }
    }
}

2、通过配置文件实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using WcfTest;

namespace WcfHosting
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof (SoapService)))
            {
                host.Opened += delegate
                {
                    Console.WriteLine("service started, press enter to exit.");
                };
                host.Open();
                Console.Read();
            }
        }
    }
}

app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:9999/neohope/metadata" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="metadataBehavior" name="WcfTest.SoapService">
        <endpoint address="http://127.0.0.9999/neohope" binding="wsHttpBinding"
                  contract="WcfTest.ISoapService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

WCF修改SOAP命名空间

有三个地方可以修改SOAP的命名空间:

1、ServiceContract

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Configuration;

namespace WcfTest
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract(Name="SoapService",Namespace="http://wcftest.neohope.org")]
    public interface ISoapService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "User/Get/{uid}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        NUser GetUser(String uid);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/User", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string UpdateUser(NUser newuser);


        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "/User", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string AddUser(NUser newuser);


        [OperationContract]
        [WebInvoke(Method = "DELETE", UriTemplate = "/User", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string DeleteUser(String uid);
    }

    [ServiceBehavior(Name = "SoapService", Namespace = "http://wcftest.neohope.org")]
    [DataContract]
    public class NUser
    {
        string uid = "";
        string uname = "";
        string usex = "";

        [DataMember]
        public String Uid
        {
            get { return uid; }
            set { uid = value; }
        }

        [DataMember]
        public string UName
        {
            get { return uname; }
            set { uname = value; }
        }

        [DataMember]
        public string USex
        {
            get { return usex; }
            set { usex = value; }
        }
    }
}

2、服务实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfTest
{
    [ServiceBehavior(Name = "SoapService", Namespace = "http://wcftest.neohope.org")]
   public class SoapService : ISoapService
    {
        static List<NUser> users = new List<NUser>();

        static SoapService()
        {
            NUser aNUser = new NUser();
            aNUser.Uid = "001";
            aNUser.UName = "张三";
            aNUser.USex = "男";
            users.Add(aNUser);
        }

        public NUser GetUser(string uid)
        {
            foreach (NUser nuser in users)
            {
                if (nuser.Uid == uid)
                {
                    return nuser;
                }
            }

            return null;
        }

        public string UpdateUser(NUser newuser)
        {
            if (newuser == null)
            {
                return "nuewuser is null";
            }

            foreach (NUser nuser in users)
            {
                if (nuser.Uid == newuser.Uid)
                {
                    nuser.UName = newuser.UName;
                    newuser.USex = nuser.USex;
                    return "User updated";
                }
            }

            return "User not found";
        }

        public string AddUser(NUser newuser)
        {
            if (newuser == null)
            {
                return "nuewuser is null";
            }

            foreach (NUser nuser in users)
            {
                if (nuser.Uid == newuser.Uid)
                {
                    nuser.UName = newuser.UName;
                    newuser.USex = nuser.USex;
                    return "User updated";
                }
            }

            users.Add(newuser);

            return "User added";
        }

        public string DeleteUser(String uid)
        {
            bool bFound = false;
            for(int i=users.Count-1;i>=0;i--)
            {
                if (users[i].Uid == uid)
                {
                    bFound = true;
                    users.RemoveAt(i);
                }
            }

            if (!bFound)
            {
                return "User Not Found";
            }
            else
            {
                return "User Deleted";
            }
        }
    }
}

3、Web.config

<?xml version="1.0"?>
<configuration>
  
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  
  <system.serviceModel>

    <services>
      <service name="WcfTest.SoapService">
        <endpoint binding="webHttpBinding" contract="WcfTest.ISoapService" bindingNamespace="http://wcftest.neohope.org"/>
      </service>
    </services>
 
    <behaviors>
      <endpointBehaviors>
      </endpointBehaviors>
      
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

AXIS2跳过HTTPS证书验证的几种方式

AXIS2启用HTTPS,只需要设置truststore及密码,然后对于HTTPS协议,就会自动启用SSL通信了。

System.setProperty("javax.net.ssl.trustStore", PATH_TO_TRUSTSTORE);        
System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD_OF_TRUSTSTORE);

但有时,基于种种原因,比如证书链有问题,比如证书HOST有问题,比如证书本身就有问题,说多了都是泪,这是后就要绕过HTTPS的证书验证了。总起来说,AXIS2有下面几种方式可以跳过HTTPS证书验证:

1、通过设置TrustAllTrustManager来绕过证书验证
这是一种局部设置方式,方式适合用wsdl2java生成stub代码的程序来执行,比如,客户端可以:

SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, new TrustManager[] {new TrustAllTrustManager()}, null);
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER,
    new Protocol("https",(ProtocolSocketFactory)new SSLProtocolSocketFactory(sslCtx),443));

2、通过设置CUSTOM_PROTOCOL_HANDLER来绕过证书验证
这是一种全局设置的方式。

Protocol myProtocolHandler = new Protocol("https", new NeoSecureSocketFactory(), 443);
//中心端注册CUSTOM_PROTOCOL_HANDLER
messageContext.getOptions().setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, myProtocolHandler);
//客户端注册CUSTOM_PROTOCOL_HANDLER
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, myProtocolHandler); 

3、注册Protocol来绕过证书验证
这是一种全局设置的方式。

Protocol.registerProtocol("https", new Protocol("https", new NeoSecureSocketFactory(), 443)); 

4、最后是NeoSecureSocketFactory.java

package com.neohope.axis2test;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.SocketFactory;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

/**
 *
 * @author Hansen
 */
public class NeoSecureSocketFactory implements ProtocolSocketFactory {
    
    private static SSLContext ssl = null;  
    
    private static TrustManager[ ] getTrustManagers() {
        TrustManager[ ] certs = new TrustManager[ ] {
                new X509TrustManager() {
                    public X509Certificate[ ] getAcceptedIssuers() { return null; }
                    public void checkClientTrusted(X509Certificate[ ] certs, String t) { }
                    public void checkServerTrusted(X509Certificate[ ] certs, String t) { }
                }
        };
        return certs;
    }
    
    private static SSLContext createSSLContext() {  
        try {  
            TrustManager[] trustManagers = getTrustManagers();  
            SSLContext sslContext = SSLContext.getInstance("TLS");  
            sslContext.init(null, trustManagers, null);  
  
            return sslContext;  
        } catch (KeyManagementException e) {  
            ; 
        } catch (NoSuchAlgorithmException e) { 
            ;
        }
        return null;  
    }  
  
    private static SSLContext getSSLContext() {  
        if (ssl == null) {  
            ssl = createSSLContext();  
        }  
        return ssl;  
    }  

    @Override
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port,  
                clientHost, clientPort); 
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
        if (params == null) {  
            throw new IllegalArgumentException("Parameters may not be null");  
        }  
        int timeout = params.getConnectionTimeout();  
        SocketFactory socketfactory = getSSLContext().getSocketFactory();  
        if (timeout == 0) {  
            return socketfactory.createSocket(host, port, clientHost,  
                    clientPort);  
        }  
  
        Socket socket = socketfactory.createSocket();  
        SocketAddress localaddr = new InetSocketAddress(clientHost, clientPort);  
        SocketAddress remoteaddr = new InetSocketAddress(host, port);  
        socket.bind(localaddr);  
        try {  
            socket.connect(remoteaddr, timeout);  
        } catch (Exception e) {  
            throw new ConnectTimeoutException(e.getMessage(), e);  
        }  
  
        return socket;  
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
         return getSSLContext().getSocketFactory().createSocket(host, port); 
    }
}

AXIS2无法从SOAP MTOM/XOP消息中获取附件

最近,同事在与其他厂商做IHE测试,测试的CASE多数都可以通过。唯独一个测试无法通过:对方需要通过MTOM/XOP消息发送一个文件到我们的服务,我们可以正常的收到消息,但无法解析消息得到附件。

经过沟通,发现另一个厂商居然是用CPP自己手动拼接的SOAP消息,也是醉了。

首先是解决了几个命名空间填写不正确的问题,调整完毕以后,AXIS2会报下面的错误:

org.apache.axiom.om.OMException: javax.xml.stream.XMLStreamException: Expected xop:Include as the sole child of an element information item (see section 3.2 of http://www.w3.org/TR/xop10/). This is due to the fact that the element (<xdsb:Document id="Document01">   </xdsb:Document>)  (OMElement obtained after axis2 processing)  that should contains the base64 value of document, is empty. But observing the same message sniffed from wireshark it seems that the Document is present.

这个问题好诡异啊。

经过一番搜索,在apache找到了答案:
由于对方发送附件时,多了一个换行符(XOP协议明确规定不允许的),导致了该错误的发生:

<xdsb:Document id="Document01"><xop:Include href="cid:1.11a262e2-bf65-1e01-28a7-000c29c7ee2b@apache.org" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
</xdsb:Document>

去掉换行符以后,就好了:

<xdsb:Document id="Document01"><xop:Include href="cid:1.11a262e2-bf65-1e01-28a7-000c29c7ee2b@apache.org" xmlns:xop="http://www.w3.org/2004/08/xop/include"/></xdsb:Document>

这个也是醉了。

大家如果收发SOAP消息,还是不要手工拼接这样写的好啊。

WSDL生成代码

1、axis2 java

rem axis2 生成client代码
wsdl2java -uri file:///C:/Users/Hansen/Desktop/test.wsdl
rem axis2 生成server代码
wsdl2java -ss -uri file:///C:/Users/Hansen/Desktop/test.wsdl

2、cxf java

rem jaxws2.2 生成代码
wsdl2java  -p com.neohope -d src -all PATH_TO_WSDL
rem jaxws2.1 生成代码
wsdl2java  -frontend jaxws21 -p com.neohope -d src -all PATH_TO_WSDL

3、wsdl soap csharp

rem cs生成client代码
wsdl C:/Users/Hansen/Desktop/test.wsdl
rem cs生成server代码
wsdl /serverInterface C:/Users/Hansen/Desktop/test.wsdl

4、svcutil wcf csharp

svcutil.exe http://localhost:1168/Service1.xamlx?wsdl /out:MyService.cs /config:app.config

使用时,WCF服务端直接实现服务接口即可。
WCF客户端,将app.config文件拷贝到项目中,然后直接调用代理类中的方法即可。

C# Https Soap Client

1、Soap Https Soap Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace IISSoapClientTest
{
    class Program
    {
        public static void HelloHttp(string url)
        {
            Hello h = new Hello(url);
            string ans = h.HelloWorld("C# http client");
            Console.WriteLine(ans);
            Console.WriteLine();
        }

        //同样的证书,IIS可以过,Tomcat过不去
        public static void HelloHttps(string url,String certPath)
        {
            X509CertificateCollection certs = new X509CertificateCollection();
            X509Certificate cert = X509Certificate.CreateFromCertFile(certPath);

            Hello h = new Hello(url);
            h.ClientCertificates.Add(cert);
            string ans = h.HelloWorld("C# https client");
            Console.WriteLine(ans);
            Console.WriteLine();
        }

        //绕过证书检查
        public static void HelloHttpsWithRemoteCertificateValidationCallback(string url)
        {
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);

            Hello h = new Hello(url);
            string ans = h.HelloWorld("C# https client");
            Console.WriteLine(ans);
            Console.WriteLine();
        }

        private static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, 
            X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }  

        static void Main(string[] args)
        {
            //HelloHttp("http://127.0.0.1:80/Hello.asmx");
            //HelloHttps("https://127.0.0.1:443/Hello.asmx");
            //HelloHttpsWithRemoteCertificateValidationCallback("https://127.0.0.1:443/Hello.asmx");

            //HelloHttp("http://127.0.0.1:8080/SoapTest/services/HelloService");
            HelloHttps("https://127.0.0.1:8443/SoapTest/services/HelloService", @"D:\DiskE\Projects\VS2010\TestProjects\SSLSocket\myKeyStore.cer");
            //HelloHttpsWithRemoteCertificateValidationCallback("https://127.0.0.1:8443/SoapTest/services/HelloService");
        }
    }
}

Java Https Soap Server(Tomcat-Axis2)

1、%Tomcat%/server/server.xml
找到下面一段:

<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
-->

替换为:

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"  
	    maxThreads="150" scheme="https"  secure="true"
	    clientAuth="false" sslProtocol="TLS"
	    disableUploadTimeout="true" enableLookups="false"
	    keystoreFile="D:/JavaContainer/apache-tomcat-6.0.35-x86/myKeyStore.jks"
	    keystorePass="sslTestPwd"
/>

这样,就可以用https://127.0.0.1:8443访问Tomcat了。

2、在需要使用https项目的axis2.xml文件中,增加下面内容

        <!--修改-->
	<transportReceiver name="http"
		class="org.apache.axis2.transport.http.AxisServletListener">
		<parameter name="port">8080</parameter>
	</transportReceiver>
        <!--新增-->
	<transportReceiver name="https"
		class="org.apache.axis2.transport.http.AxisServletListener">
		<parameter name="port">8443</parameter>
	</transportReceiver>

这样,该WebService就可以使用https进行访问了:)

C# Https Soap Server(IIS7)

1、首先准备一个p12格式的服务端证书
无论是购买,还是用openssl或java keytool生成自签名证书都可以

2、在IIS7的根目录,选中“安全性->根目录证书”,选择“导入”即可

3、如果显示证书链有问题,则在IE中导入CA证书就好了

4、在需要HTTPS的网站上,选择“绑定”,绑定类型为https,选择需要的证书

5、在客户端的IE中,导入CA证书就好了

Java Https Soap Client(Axis2)

1、SoapClient

package com.neohope;

import java.net.URL;
import java.rmi.RemoteException;

public class SoapClientTest {
	
	public static void HelloHttp(String url) throws RemoteException
	{
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java http client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	public static void HelloHttps(String url,String trustStorePath,String trustStorePwd) throws RemoteException
	{
		URL jksurl = SoapClientTest.class.getClassLoader().getResource(
				"myTrustStore.jks");
		String jks = jksurl.getFile();
		System.setProperty("javax.net.ssl.trustStore", jks);
		System.setProperty("javax.net.ssl.trustStorePassword", trustStorePwd);
		
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java https client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	
	public static void main(String[] args) throws RemoteException
	{
		//HelloHttp("http://localhost:80/Hello.asmx");
		HelloHttps("https://localhost:443/Hello.asmx","myTrustStore.jks","sslTestPwd");
	}
}

2、SoapClientWithContextTest

package com.neohope;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class SoapClientWithContextTest {
	
	public static void HelloHttp(String url) throws RemoteException
	{
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java http client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	public static void HelloHttps(String url,String trustStorePath,String trustStorePwd) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{
		URL jksurl = SoapClientTest.class.getClassLoader().getResource(
				"myTrustStore.jks");
		String jks = jksurl.getFile();
		
		KeyStore trustStore = KeyStore.getInstance("JKS");
		trustStore.load(new FileInputStream(jks), trustStorePwd.toCharArray());
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
		trustManagerFactory.init(trustStore);
        
		SSLContext sslContext = SSLContext.getInstance("TLSv1");
		//SSLContext sslContext = SSLContext.getInstance("SSLv3");
		
		sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), null);
		SSLContext.setDefault(sslContext);
		
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java https client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{
		//HelloHttp("http://localhost:80/Hello.asmx");
		HelloHttps("https://localhost:443/Hello.asmx","myTrustStore.jks","sslTestPwd");
	}
}

3、SoapClientWithTrustManagerTest
可以绕过证书检查

package com.neohope;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SoapClientWithTrustManagerTest {
	
	public static void HelloHttp(String url) throws RemoteException
	{
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java http client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	public static void HelloHttps(String url,String trustStorePath,String trustStorePwd) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{        
		SSLContext sslContext = SSLContext.getInstance("TLSv1");
		//SSLContext sslContext = SSLContext.getInstance("SSLv3");
		
		sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
		SSLContext.setDefault(sslContext);
		
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java https client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	private static class DefaultTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}
	
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{
		//HelloHttp("http://localhost:80/Hello.asmx");
		HelloHttps("https://localhost:443/Hello.asmx","myTrustStore.jks","sslTestPwd");
	}
}

Axis2 WebService Client

1、Axis2调用WebService一般有两种方法:
a、使用org.apache.axis2.rpc.client.RPCServiceClient自动生成PayLoad
b、使用org.apache.axis2.client.ServiceClient手动生成PayLoad

package com.ats.ws.client;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.log4j.Logger;

import com.ats.db.Person;
import com.ats.db.PersonAddResponse;

public class WSInvoker
{
	private static Logger logger = Logger.getLogger(WSInvoker.class);
	
	private static void invokeWebServiceRPC()
	{
		try
		{
			RPCServiceClient serviceClient = new RPCServiceClient();
			Options options = serviceClient.getOptions();
			options.setTo(new EndpointReference("http://localhost:8080/WebService1/services/PersonManager"));

			// 调用Action
			QName operation = new QName("http://ws.ats.com", "PersonAdd");

			// 调用参数类型和参数值
			Person p = new Person();
			Object req[] = new Object[] { p };
			p.setName("HI");
			Class[] reqClasses = new Class[] { PersonAddResponse.class };

			// 返回结果
			Object[] rsp = serviceClient.invokeBlocking(operation, req, reqClasses);
			PersonAddResponse r = (PersonAddResponse) rsp[0];
			logger.debug(r.getOperationReult());

		} catch (AxisFault e)
		{
			e.printStackTrace();
		}
	}

	public static void invokeWebServiceDocument()
	{
		try
		{
			ServiceClient serviceClient = new ServiceClient();
			Options opts = new Options();
			opts.setTo(new EndpointReference("http://localhost:8080/WebService1/services/PersonManager"));
			opts.setAction("urn:PersonAdd");
			serviceClient.setOptions(opts);

			// 发送请求并并得到返回结果
			OMElement res = serviceClient.sendReceive(createPayLoad());
			logger.debug(res.getFirstElement().getText());
		} catch (AxisFault e)
		{
			e.printStackTrace();
		}
	}

	public static OMElement createPayLoad()
	{
		OMFactory fac = OMAbstractFactory.getOMFactory();
		// 命名空间
		OMNamespace omNsXSD = fac.createOMNamespace("http://ws.ats.com", "xsd");
		OMNamespace omNsXS = fac.createOMNamespace("http://www.w3.org/2001/XMLSchema", "xs");
		// 指定方法
		OMElement method = fac.createOMElement("PersonAdd", omNsXSD);
		// 指定方法的参数
		OMElement p1 = fac.createOMElement("person", omNsXS);
		
		OMElement personName = fac.createOMElement("personName", omNsXS);
		personName.setText("personName");
		p1.addChild(personName);
		OMElement personid=fac.createOMElement("personid", omNsXS);
		personid.setText("");
		p1.addChild(personid);
		
		method.addChild(p1);
		return method;
	}

	public static void main(String[] args)
	{
		WSInvoker.invokeWebServiceRPC();
		WSInvoker.invokeWebServiceDocument();
	}
}

2、要想看到网络通讯的话,在log4j的配置文件中增加:

	<category name="org.apache.commons.httpclient">
		<priority value="WARN" />
	</category>
	<category name="httpclient.wire">
		<priority value="DEBUG" />
	</category>