java调用webService方法

一、服务器参数简单的调用,比如参数只有arg0、arg1或者esb:input

soapUi连接样子:

1.pom依赖

      <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>3.1.8</version>
      </dependency>
      <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.8</version>
      </dependency>

2.新建重新编码的java文件JAXDynamicClientFactory

package com.emr.controller;

import org.apache.cxf.Bus;
import org.apache.cxf.bus.CXFBusFactory;
import org.apache.cxf.endpoint.EndpointImplFactory;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
import org.apache.cxf.jaxws.support.JaxWsEndpointImplFactory;

import java.util.List;


public class JAXDynamicClientFactory extends DynamicClientFactory {
    protected JAXDynamicClientFactory(Bus bus) {
        super(bus);
    }

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

    protected boolean allowWrapperOps() {
        return true;
    }

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

    public static JAXDynamicClientFactory newInstance() {
        Bus bus = CXFBusFactory.getThreadDefaultBus();
        return new JAXDynamicClientFactory(bus);
    }
    public boolean compileJavaSrc(String classPath, List srcList, String dest) {
        org.apache.cxf.common.util.Compiler javaCompiler
                = new org.apache.cxf.common.util.Compiler();
        javaCompiler.setEncoding("UTF-8");
        javaCompiler.setClassPath(classPath);
        javaCompiler.setOutputDir(dest);
        javaCompiler.setTarget("1.8");
        return javaCompiler.compileFiles(srcList);
    }
}

3.调用:

//创建连接工厂
JAXDynamicClientFactory dcf = JAXDynamicClientFactory.newInstance();
//创建客户端 wsUrl为webService接口地址
Client client = dcf.createClient(wsUrl);
//动态调用方法,wsMethod为调用webService接口的方法名,params是参数名称,支持多个
Object[] objects = client.invoke(wsMethod,params...);
//销毁连接
client.destroy();
//接收结果
String result = objects[0].toString();
System.out.println("result:"+result);

二、参数指定 

soapUi连接样子:

1.pom.xml依赖

        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-discovery</groupId>
            <artifactId>commons-discovery</artifactId>
            <version>0.2</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis-jaxrpc</artifactId>
            <version>1.4</version>
        </dependency>

2.示例。参数配置/dataConfig/pushConfig.json

{
  "steelPhone": "1",
  "backAllCode": "3",
  "requestUrls":[
    {
      "back_third": "1",
      "wsMethod": "ChasMessageServer",
      "parameters":["recordReturn"],
      "parameterNames": ["action","message"],
      "namespance": "http://webservice.http.plugins.api.his.karrytech.com/",
      "requestUrl": "http://192.9.100.32:9022/ktin/api/webservice/ChasWebService?wsdl"
    },
    {
      "back_third": "2",
      "wsMethod": "sendUnlockInfo",
      "parameters":[],
      "parameterNames": ["json"],
      "namespance": "http://ws.nis.ewell/",
      "requestUrl": "http://192.9.194.186:5656/NIS_GuangdongZY//EwellInterfaceService?wsdl"
    }
  ]
}

3.使用:

package com.docus.services.system.pushUtil;

import java.io.*;

/**
 * json工具类
 */
public class JsonUtils {

    /**
     * 读取json文件方法
     * @param fileName:json文件存在的本地地址
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        Reader reader=null;
        FileReader fileReader=null;
        try {
            File jsonFile = new File(fileName);
            fileReader = new FileReader(jsonFile);
            reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                reader.close();
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
    private static String CurrentPath() {
        File dir = new File(".");
        String currentpath = "";
        try {
            currentpath = dir.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return currentpath;
    }
    //请求地址
     String wsUrl="";
    //命名空间
     String namespance= "";
    // 推送方法名
     String wsMethod ="";
    //解析json映射文件
    String json = JsonUtils.readJsonFile(CurrentPath() +     "\\dataConfig\\pushConfig.json");
    Map jsonMap = JSON.parseObject(json, Map.class);
    List<requestUrls> collectLists =             JSON.parseArray(String.valueOf(jsonMap.get("requestUrls")), requestUrls.class);
    for (requestUrls collectList : collectLists) {
        wsUrl=collectList.getRequestUrl();
        namespance=collectList.getNamespance();
        wsMethod=collectList.getWsMethod();
        HashMap<String, Object> map = new HashMap<>();
        map.put("jzh",basic.getJzh());
        map.put("admissTimes",basic.getAdmissTimes());
        map.put("inpatientNo",basic.getInpatientNo());
        map.put("deptCode",basic.getDisDept());
        map.put("deptName",basic.getDisDeptName());
        map.put("roleCode",flowNodesInfo.getBackThird());
        map.put("backType",clinicFlowBackDto.getClassifyName());
        map.put("backDescribe",flowNodesInfo.getFromText()+"退回");
        map.put("backReason","缺陷信息:"+clinicFlowBackDto.getClassifyName()+","+clinicFlowBackDto.getBackContent());
        map.put("backer",userName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strData = sdf.format(new Date());
        map.put("backTime",strData);
        String wsParam = JSON.toJSONString(map);
        List<String> parameters = collectList.getParameters();
        List<String> parameterNames = collectList.getParameterNames();
        Object[] params;
        if (CollectionUtils.isEmpty(parameters)) {
            params = new Object[1];
            params[0]=wsParam;
        }else{
            params = new Object[parameters.size()+1];
            for (int i = 0; i < parameters.size(); i++) {
                params[i]=parameters.get(i);
            }
            params[parameters.size()]=wsParam;
        }
        String result = requestFunctionWebService(params,wsUrl,wsMethod,namespance,parameterNames);
        log.info("得到的结果:"+result);
    }
private String requestFunctionWebService(Object[] params,String url,String methodName,String namespance,List<String> parameterNames) {
        String result = "";
        if(null != params) {
            try {
                org.apache.axis.client.Service service = new org.apache.axis.client.Service();
                Call call = (Call) service.createCall();
                call.setTargetEndpointAddress(url);
                call.setOperationName(new QName(namespance, methodName));
                for (int i = 0; i < parameterNames.size(); i++) {
                    call.addParameter(parameterNames.get(i), XMLType.XSD_STRING, ParameterMode.IN);//接口的参数
                }
                call.setReturnType(XMLType.XSD_STRING);//设置返回类型
                result = (String) call.invoke(params);
            } catch (Exception e) {
                e.printStackTrace();
                //方法名
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                e.printStackTrace(new PrintStream(baos));
                String exception = baos.toString();
                log.error("requestFunctionWebService请求接口异常:"+exception);
            }
        }
        return result;
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值