java调用c#webservice接口,所遇见的问题

1.java端所使用的的框架为springboot
2.springboot 集成的cxf

 <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>3.2.0</version>
 </dependency>

这里使用集成了cxf的依赖,可以根据的jdk以及springboot 选择合适的cxf版本,如果使用jdk9或者9以上会有问题
使用cxf我们可以进行服务的一个发布,以及服务的一个调用
(1).服务发布代码案例

package com.wms.webService;

import com.wms.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class WebServer implements ApplicationRunner {
	
    @Value("${wms.business.url=com.base.intface}")
    String baseFilePath;
	//发布调用的路径 0.0.0.0 表示是本地 
    @Value("${webservice.address=http://10.6.10.75}")
    String address;
	//访问webservice 接口端口
    @Value("${webservice.port=8899}")
    Integer port;
	//相当于和address拼接后的 http://10.6.10.75/rest
    @Value("${webservice.path=/rest}")
    String path;

    String fullPath;

    Boolean inited = false;

    @Autowired
    ConfigService configService;
	//这里是通过读取数据看的配置进行发布的  其字符串对应的value :  /beixin:MoveTask
    final String wmsWebServiceMaps = "wms.webService.maps";

    @PostConstruct
    synchronized void init() {
        log.info("init() begin");
        try {
            inited = false;
            fullPath = String.format("%s:%s%s", address, port, path);
            inited = true;
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            throw e;
        } finally {
            log.info("init() end");
        }
    }

    ConcurrentHashMap<String, Class> webMap = new ConcurrentHashMap<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("run() begin");
        try {
            Reflections reflections = new Reflections(baseFilePath);
            Set<Class<?>> clazzes = reflections.getTypesAnnotatedWith(WebService.class);
            if (null == clazzes || clazzes.isEmpty()) {
                log.warn("There is no WebService annotated class");
                return;
            }

            String mapStr = configService.getValue(wmsWebServiceMaps);
            if (mapStr != null && !mapStr.trim().isEmpty()) {
                String[] maps = mapStr != null && !mapStr.trim().isEmpty() ? mapStr.trim().split(",") : new String[]{};
                for (String map : maps) {
                    String[] pair = map.split(":");
                    if (pair != null && pair.length >= 2) {
                        for (Class clazz : clazzes) {
                            String className = clazz.getName();
                            if (className.equals(String.format("%s.%s", baseFilePath, pair[1]))) {
                                String webUrl = String.format("%s%s", fullPath, pair[0]);
                                webMap.put(webUrl, clazz);
                            }
                        }
                    }
                }
            }

            for (String s : webMap.keySet()) {
                Endpoint.publish(s, webMap.get(s).newInstance());
            }
        } finally {
            log.info("run() end");
        }
    }
}

利用这个发布出来的服务为这样就会告诉你发布出来的接口是哪个,其调用路径 为
http://10.6.10.75:9090/rest/beixin/MoveTask?wsdl

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:beix="http://beixin.business.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <beix:SendInstructions>
         <!--Optional:-->
         <arg0>1-0-0</arg0>
         <!--Optional:-->
         <arg1>1-0-48</arg1>
         <!--Optional:-->
         <arg2>002</arg2>
         <arg3>2</arg3>
      </beix:SendInstructions>
   </soapenv:Body>
</soapenv:Envelope>

请求头一定要配置的
Content-Type

application/soap+xml; charset=utf-8
postman调用接口

@WebService
@Slf4j
public class MoveTask {
    /* 这里就是postman 测试传参数 arg0 代表参数列表中的第一个 以此类推
    请求头里边加:
    Content-Type     application/soap+xml; charset=utf-8
    //访问路径案例:http://localhost:9090/rest/beixin/MoveTask?wsdl
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:beix="http://beixin.business.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <beix:SendInstructions>
         <!--Optional:-->
         <arg0>1-0-1</arg0>
         <!--Optional:-->
         <arg1>1-0-3</arg1>
         <!--Optional:-->
         <arg2>008</arg2>
         <arg3>158</arg3>
      </beix:SendInstructions>
   </soapenv:Body>
</soapenv:Envelope>*/
    @WebMethod
    public String SendInstructions(String starLocation, String endLocation, String salver, int taskId) {
		return "调用服务成功";
    }

如果要调用c#的webservice 案例为---->

package com.wms.webService;

import com.alibaba.fastjson.JSONObject;
import com.mrrobotics.utils.response.GeneralResponse;
import com.wms.webService.WebClient;
import org.junit.Test;

public class webClientTest {

//    @Test
//    public void contextLoads() {
//        Object[] objects = WebClient.invoke1("http://127.0.0.1:9090/rest/test?wsdl", "test", "This is a web service test");
//        System.out.println("====打印:"+objects[0]);
//
//        GeneralResponse response = WebClient.invoke2("http://127.0.0.1:9090/rest/test?wsdl", "test", "This is a web service test");
//        System.out.println("====请求:"+response);
//    }
//    @Test
//    public void contextLoads() {
//        Object[] objects = WebClient.invoke1("http://127.0.0.1:9090/rest/beixin/MoveTask?wsdl", "SendInstructions", "1","2","3",4);
//        System.out.println("====打印:"+objects[0]);
//
        GeneralResponse response = WebClient.invoke2("http://127.0.0.1:9090/rest/test?wsdl", "test", "This is a web service test");
        System.out.println("====请求:"+response);
//    }
    @Test
    public void contextLoads() {
//        Object[] objects = WebClient.invoke1("http://127.0.0.1:9090/rest/beixin/MoveTask?wsdl", "SendInstructions", "1","2","3",4);
//        System.out.println("====打印:"+objects[0]);

//        Object[] reportCompleteds = WebClient.invoke1("http://10.6.10.75:5678/WebService1.asmx?wsdl", "ReportCompleted", "111", 2, 2);
//        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(reportCompleteds[0]);
//        System.out.println("===========上报agv的================"+jsonObject.toString());



//        Object[] reportCompleteds1 = WebClient.invoke1("http://10.6.10.75:5678/WebService1.asmx?wsdl", "InboundRequest", "111", 2);
//        JSONObject jsonObject1 = (JSONObject) JSONObject.toJSON(reportCompleteds1[0]);
//        System.out.println("===========入库请求================"+jsonObject1.toString());



        Object[] reportCompleteds2 = WebClient.invoke1("http://10.6.10.75:5678/WebService1.asmx?wsdl", "GetSignal", "111", 2);
        JSONObject jsonObject2 = (JSONObject) JSONObject.toJSON(reportCompleteds2[0]);
        System.out.println("===========信号获取================"+jsonObject2.toString());

//        GeneralResponse response = WebClient.invoke2("http://127.0.0.1:9090/rest/test?wsdl", "test", "This is a web service test");
//        System.out.println("====请求:"+response);
    }
}

这样调用c#的webservice,其依赖的两个类如下
第一个类:

import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.common.util.Compiler;
import org.apache.cxf.endpoint.EndpointImplFactory;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
import org.apache.cxf.jaxws.support.JaxWsEndpointImplFactory;

import java.io.File;
import java.util.List;

public class MyJaxWsDynamicClientFactory extends DynamicClientFactory {

    protected MyJaxWsDynamicClientFactory(Bus bus) {
        super(bus);
    }

    protected EndpointImplFactory getEndpointImplFactory() {
        return JaxWsEndpointImplFactory.getSingleton();
    }

    protected boolean allowWrapperOps() {
        return true;
    }

    public static MyJaxWsDynamicClientFactory newInstance(Bus b) {
        return new MyJaxWsDynamicClientFactory(b);
    }

    public static MyJaxWsDynamicClientFactory newInstance() {
        Bus bus = BusFactory.getThreadDefaultBus();
        return new MyJaxWsDynamicClientFactory(bus);
    }

    /*
     * 在 Windows 系统的使用 CXF 动态客户端时可能会遇到 tomcat 启动后调用 wsdl 遇到 很多错误GBK编码,
     * 这个错误的原因是 由于项目 maven 配置使用 UTF-8 的,CXF 生成java 文件是使用的UTF-8 的编码,
     * 而使用javac 编译的时候 取的是系统默认的编码 由于中文 window 系统采用GBK 编码,所有就相当于使用javac -encoding gbk .java,所有就出 出现乱码
     */
    @Override
    protected boolean compileJavaSrc(String classPath, List<File> srcList, String dest) {
        System.out.println("==========用于编辑编码问题的东西========");
        Compiler javaCompiler = new Compiler();
        // 设置编码格式
        javaCompiler.setEncoding("UTF-8");
        javaCompiler.setClassPath(classPath);
        javaCompiler.setOutputDir(dest);
        if (System.getProperty("java.version").startsWith("9")) {
            javaCompiler.setTarget("9");
        } else {
            javaCompiler.setTarget("1.8");
        }

        return javaCompiler.compileFiles(srcList);
    }
}

第二个类:

package com.wms.webService;

import com.alibaba.fastjson.JSONObject;
import com.mrrobotics.utils.response.GeneralResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;

@Slf4j
public class WebClient {

    public static Object[] invoke1(String wsdlUrl, String method, Object... params) {
        // 创建动态客户端
        MyJaxWsDynamicClientFactory dcf = MyJaxWsDynamicClientFactory.newInstance();
        try {
            Client client = dcf.createClient(wsdlUrl);
            // 需要密码的情况需要加上用户名和密码
            // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
            // invoke("方法名",参数1,参数2,参数3....);
            Object[] objects = client.invoke(method, params);
            client.destroy();
            return objects;
        } catch (java.lang.Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    public static GeneralResponse invoke2(String wsdlUrl, String method, Object... params) {
        Object[] objects = invoke1(wsdlUrl, method, params);
        if (null == objects) {
            return GeneralResponse.failure("失败");
        }

        JSONObject jsonObject = null;
        if (objects.length > 0) {
            jsonObject = new JSONObject();
            if (objects.length == 1) {
                jsonObject.put("data", objects[0]);
            } else {
                jsonObject.put("data", objects);
            }
            return GeneralResponse.success(jsonObject.get("data"));
        }
        return GeneralResponse.success(jsonObject);
    }
}

第一个类还对其如果调用c#的乱码问题以及调用调不动问题
java.lang.IllegalStateException:Unable to create schema compiler
从jdk环境入手 jdk8 下会有两个文件夹
jdk和jre
jdk的lib下有一个tools.jar包 把这个包放在jre的lib文件下就好了 就是 复制过去然后可以运行成功

咱的文采不是很好,希望大家还是好好的看看注释,多多理解,这展现的就是一个思想,好了本次分享完毕,希望下次再见

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值