zoukankan      html  css  js  c++  java
  • Java调用wcf

    最近正在学习wcf,java平台、android、mac都要调用,今天先弄个java调用测试下。

    一、创建WCF

    C# Code
    namespace YourNamespace
    {
        // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IHello”。
        [ServiceContract(Namespace = "http://xxx.com/")]
        public interface IHello
        {
            [OperationContract]
            string SayHello(string words);
    
            [OperationContract]
            string Test();
    
        }
    }
    C# Code
    namespace YourNamespace
    {
        // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Hello”。
        public class Hello : IHello
        {
            public string SayHello(string words)
            {
                return "hello " + words;
            }
    
            public string Test()
            {
                return "test wcf";
            }
        }
    }
    C# Code
    <%@ ServiceHost Language="C#" Debug="true" Service="YourNamespace.Hello" CodeBehind="Hello.svc.cs" %>
    web.config
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.serviceModel>
        <serviceHostingEnvironment>
          <serviceActivations >
            <add relativeAddress="Hello.svc" service="YourNamespace.Hello"/>
          </serviceActivations >
        </serviceHostingEnvironment >
    
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBindingCfg" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                  maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None"
                    realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
    
        <services>
          <service name="YourNamespace.Hello" behaviorConfiguration="ServiceBehavior">
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:90/Hello"/>
              </baseAddresses>
            </host>
            <endpoint binding="basicHttpBinding" contract="YourNamespace.IHello">
              <identity>
                <dns value="localhost" />
              </identity>
            </endpoint>
          </service>
        </services>
    
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehavior">
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
      <system.web>
        <compilation debug="true" />
      </system.web>
    </configuration>

    二、Java客户端调用

    1.下载ksoap2 下载地址 http://code.google.com/p/ksoap2-android/

    2.创建Java项目添加该类

    Java Code
    package com.xx.wcftest;
    
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    
    /**
     * 调用wcf服务类
     * @author awei
     *
     */
    public class SoapService {
        
        /**
         * wcf服务命名空间
         */
        protected String NameSpace = "http://xxx.com/";//可从配置文件读取
        
        /**
         * wcf 服务地址
         */
        protected String URL = "http://localhost:90/";//可从配置文件读取
        
        /**
         * wcf soap 方法执行地址,可从wsdl中获取
         */
        protected String SOAP_ACTION;
        
        /**
         * 功能名称
         */
        protected String MethodName;
        
        /**
         * 构造器初始化参数
         * @param svc 服务寄宿文件名称 如:Hello.svc
         * @param ServiceInterface 服务接口名称 如:IHello
         */
        public SoapService(String svc,String ServiceInterface)
        {
            this.URL += svc;
            this.SOAP_ACTION = this.NameSpace + ServiceInterface + "/";
        }
    
        /**
         * 调用wcf方法返回结果
         * @param method 要调用的方法名称
         * @param map 要调用的方法参数字典
         * @return 
         */
        public SoapObject LoadResult(String method,Map<String, Object> map) {
            this.MethodName = method;
            SoapObject soapObject = new SoapObject(NameSpace, MethodName);
            if(map != null && map.size() != 0){
                Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String,Object> entry = iter.next();
                    soapObject.addProperty(entry.getKey().toString(),entry.getValue());
                    }
            }
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // 版本
            envelope.bodyOut = soapObject;
            envelope.dotNet = true;
            envelope.setOutputSoapObject(soapObject);
            
            HttpTransportSE trans = new HttpTransportSE(URL);
            trans.debug = true; // 使用调试功能
            
            try {
                trans.call(SOAP_ACTION + this.MethodName, envelope);
                System.out.println("Call Successful!");
            } catch (Exception e) {
                System.out.println("IOException");
                e.printStackTrace();
            } 
            SoapObject result = (SoapObject) envelope.bodyIn;
            
            return result;
        }
        
    }

    3.调用服务

    Java Code
    public class HelloWcfTest {
    
        public static void main(String[] args) {
            //1.创建服务对象
            SoapService service = new SoapService("Hello.svc","IHello");
            
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("words", "awei");//SayHello方法的参数
            
            SoapObject result = service.LoadResult("SayHello", map);
            System.out.println("WCF Test返回的数据是:" + result.getProperty(0));
            
            result = service.LoadResult("SayHello", null);
            System.out.println("WCF Test返回的数据是:" + result.getProperty(0));
        }
    }
  • 相关阅读:
    display: flex
    TTStand --Variant的应用
    跨域
    HTTP 响应状态代码
    SQL Server 2017 Developer and Express
    WPF 中 通过点击ListBox中的元素自动选中一整项
    C#计算屏幕的物理宽和高
    C#常用设计模式
    EntityFrameworkCore之工作单元的封装
    内存包装类 Memory 和 Span 相关类型
  • 原文地址:https://www.cnblogs.com/aweifly/p/3026789.html
Copyright © 2011-2022 走看看