基于CXF框架的webservice接口发布与调用

 

目录

         前言

正文

一,开发接口服务端(soap风格),接收SAP系统推送过来的数据

二,调用SAP提供的webservice接口(soap风格) 

三,调用SRM系统提供的rest接口

四,接口调试工具

 ​


前言

刚入职一家公司,到了项目上,技术总监让我负责项目上的接口开发,对于之前没开发过接口的小白来说甚是惶恐,赶进恶补了下接口的相关知识,基本概念类的东西就不在记录,网上一大堆资料,本文记录下当前系统和外部SAP,SRM,OA提供的各种接口的调用和为他们提供接口的开发.项目采用SSM框架,已经集成CXF框架,这里不再赘述.

正文

一,开发接口服务端(soap风格),接收SAP系统推送过来的数据

业务需求:sap系统会定期推送业务数据到我们系统中,我们要做的就是接收他们推送过来的数据,并将它们推送的数据作为我们的业务数据进行业务操作

实现方式:建立接口表,接收数据,通过oracle存储过程将接口表中数据插入到对应的业务表中.(存储过程可以对接口数据进行筛选,校验等处理逻辑,使用起来非常灵活)

以客户接口表为例:

1.表结构

-- Create table
create table EMT_ITF_CUSTOMER
(
  iface_id              VARCHAR2(255) not null,
  batch_id              NUMBER not null,
  status                VARCHAR2(100) not null,
  message               VARCHAR2(1000),
  customer_code         VARCHAR2(100) not null,
  customer_name         VARCHAR2(100) not null,
  customer_name_alt     VARCHAR2(240),
  enable_flag           VARCHAR2(1),
  cid                   NUMBER,
  object_version_number NUMBER default 1,
  request_id            NUMBER default -1,
  program_id            NUMBER default -1,
  created_by            NUMBER default -1,
  creation_date         DATE default sysdate,
  last_updated_by       NUMBER default -1,
  last_update_date      DATE default sysdate,
  last_update_login     NUMBER default -1,
  attribute_category    VARCHAR2(30),
  color                 VARCHAR2(30),
  remark                VARCHAR2(255),
  sap_request_id        VARCHAR2(255)
)
tablespace TBS_PERM_HAP
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
-- Add comments to the table 
comment on table EMT_ITF_CUSTOMER
  is '客户接口表';
-- Add comments to the columns 
comment on column EMT_ITF_CUSTOMER.iface_id
  is '接口头表主键';
comment on column EMT_ITF_CUSTOMER.customer_code
  is '客户编码';
comment on column EMT_ITF_CUSTOMER.customer_name
  is '客户描述';
comment on column EMT_ITF_CUSTOMER.customer_name_alt
  is '简称';
comment on column EMT_ITF_CUSTOMER.enable_flag
  is '是否有效';
comment on column EMT_ITF_CUSTOMER.sap_request_id
  is 'sap请求号';

2.DTO和VO类:省略

3.接口返回VO类:

import java.io.Serializable;

public class IfaceReturnMessageVO implements Serializable {

    private static final long serialVersionUID = -7103902625775613662L;

    public IfaceReturnMessageVO() {
        this.errorCode = SuccessCode;
        this.status = Success;
        this.errorMessage = "成功";
    }
}

4.接口和实现类:

import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.List;

import emt.itf.view.IfaceReturnMessageVO;
import emt.itf.ws.view.WSCustomerVo;

@WebService
public interface IWSCustomerService {
    IfaceReturnMessageVO syncCustomerData(@WebParam(name = "vos") List<WSCustomerVo> vos);
}

 说明:

@WebService:标记表示该接口是一个WebService服务。

@WebParam(name="paramName")表示方法中的参数,name属性限制了参数的名称,若没有指定该属性,参数将会被重命名。

@WebService(endpointInterface = "emt.itf.ws.ws_customer.service.IWSCustomerService")
public class WSCustomerServiceImpl implements IWSCustomerService {
   @Override
    public IfaceReturnMessageVO syncCustomerData(List<WSCustomerVo> vos) {
        //将数据插入到接口表,省略...
        
        return ifaceReturnMessageVO;
    }
}

说明:

@WebService(endpointInterface=”对应的WebService接口的全限定名”,serviceName=”WebService的名字,自己定义,可省略”)。

 5.发布:

编写applicationContext-webservice.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ">

    <!--客户接口-->
    <bean id="rawWsCustomer" class="emt.itf.ws.ws_customer.service.impl.WSCustomerServiceImpl"/>
    <jaxws:endpoint id="rawWsCustomerEndPoint" implementor="#rawWsCustomer" address="/CustomerWs">
    </jaxws:endpoint>
   
</beans>

6.启动项目,访问地址:http://localhost:8080/ws/CustomerWs?wsdl

7.编写oracle存储过程,将接口表数据保存到业务表

CREATE OR REPLACE PACKAGE emt_syn_sap_pck IS
  PROCEDURE syn_customer_for_ui;
END emt_syn_sap_pck;
  PROCEDURE syn_customer_for_ui IS
    ln_message_id NUMBER;
  BEGIN
    ln_message_id := syn_customer;
    dbms_output.put_line('ln_message_id = ' || ln_message_id);
  END syn_customer_for_ui;
  FUNCTION syn_customer RETURN NUMBER IS
    lv_msg  VARCHAR2(300);
    lv_flag VARCHAR2(10);
    lr_data emt_customer%ROWTYPE; 
  BEGIN
    FOR lr_01 IN (SELECT t.iface_id,
                         t.batch_id,
                         t.status,
                         t.message,
                         t.customer_code,
                         t.customer_name,
                         t.customer_name_alt,
                         t.enable_flag,
                         t.rowid
                    FROM emt_itf_customer t
                   WHERE 1 = 1
                     AND nvl(t.status, 'N') = 'N' 
                   ORDER BY t.iface_id ASC) LOOP
    
      lr_data := NULL;    
      --清空消息状态
      lv_msg  := NULL;
      lv_flag := 'Y';
      lr_data.customer_id       := emt_customer_s.nextval;
      lr_data.customer_code     := lr_01.customer_code;
      lr_data.customer_name     := lr_01.customer_name;
      lr_data.customer_name_alt := lr_01.customer_name_alt;
      lr_data.enable_flag       := lr_01.enable_flag;
      lr_data.created_by        := -1;
      lr_data.creation_date     := SYSDATE;
      lr_data.last_updated_by   := -1;
      lr_data.last_update_date  := SYSDATE;
      lr_data.last_update_login := -1;    
      BEGIN
        UPDATE emt_customer t
           SET t.customer_name     = lr_data.customer_name,
               t.customer_name_alt = lr_data.customer_name_alt,
               t.enable_flag       = lr_data.enable_flag,
               t.last_update_date  = SYSDATE       
         WHERE t.customer_code = lr_data.customer_code;
        IF SQL%NOTFOUND THEN
          INSERT INTO emt_customer VALUES lr_data;
        END IF;
      EXCEPTION
        WHEN OTHERS THEN
          lv_msg  := '写入或更新错误。' || SQLCODE || '-' || SQLERRM;
          lv_flag := 'E';
          GOTO end_loop;
      END;
      <<end_loop>>
    --更新接口表状态
      UPDATE emt_itf_customer t
         SET t.status = lv_flag, t.message = lv_msg, t.last_update_date = SYSDATE
       WHERE t.rowid = lr_01.rowid;   
    END LOOP;
    RETURN 1; 
  EXCEPTION
    WHEN OTHERS THEN
    RETURN - 1; 
  END;

 8.定时执行存储过程:

begin
  sys.dbms_job.change(job => 1002,
                      what => 'begin
  emt_syn_sap_pck.syn_customer_for_ui;
end;',
                      next_date => to_date('27-04-2021 02:03:15', 'dd-mm-yyyy hh24:mi:ss'),
                      interval => 'sysdate+15/24/60');
  commit;
end;
/

 

二,调用SAP提供的webservice接口(soap风格) 

1.创建接口实体类和接口表用以保存接口数据:过程省略...

重写tostring方法用以拼接xml格式:

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(String.format("<I_STO>%s</I_STO>\n", CommonUtils.Nvl(this.getiSto(), "")));
        stringBuilder.append("<T_DELIVERY>\n");
        stringBuilder.append(String.format("<TRAOR>%s</TRAOR>\n", CommonUtils.Nvl(this.getInstructionDocNum(), "")));
        stringBuilder.append(String.format("<SERNO>%s</SERNO>\n", CommonUtils.Nvl(this.getInstructionNum(), "")));
        stringBuilder.append(String.format("<MATNR>%s</MATNR>\n", CommonUtils.Nvl(this.getMatnr(), "")));
        stringBuilder.append(String.format("<LFIMG>%s</LFIMG>\n", CommonUtils.Nvl(this.getLfimg(), "")));
        stringBuilder.append(String.format("<VRKME>%s</VRKME>\n", CommonUtils.Nvl(this.getVrkme(), "")));
        stringBuilder.append(String.format("<WERKS>%s</WERKS>\n", CommonUtils.Nvl(this.getWerks(), "")));
        stringBuilder.append(String.format("<LGORT>%s</LGORT>\n", CommonUtils.Nvl(this.getLgort(), "")));
        stringBuilder.append(String.format("<CHARG>%s</CHARG>\n", CommonUtils.Nvl(this.getCharg(), "")));
        stringBuilder.append(String.format("<LGMNG>%s</LGMNG>\n", CommonUtils.Nvl(this.getLgmng(), "")));
        stringBuilder.append(String.format("<MEINS>%s</MEINS>\n", CommonUtils.Nvl(this.getMeins(), "")));
        stringBuilder.append(String.format("<VGBEL>%s</VGBEL>\n", CommonUtils.Nvl(this.getVgbel(), "")));
        stringBuilder.append(String.format("<VGPOS>%s</VGPOS>\n", CommonUtils.Nvl(this.getVgpos(), "")));
        stringBuilder.append(String.format("<BRGEW>%s</BRGEW>\n", CommonUtils.Nvl(this.getBrgew(), "")));
        stringBuilder.append(String.format("<GEWEI>%s</GEWEI>\n", CommonUtils.Nvl(this.getGewei(), "")));
        stringBuilder.append(String.format("<VBELN>%s</VBELN>\n", CommonUtils.Nvl(this.getVbeln1(), "")));
        stringBuilder.append(String.format("<POSNR>%s</POSNR>\n", CommonUtils.Nvl(this.getPosnr1(), "")));
        stringBuilder.append(String.format("<ZDELE>%s</ZDELE>\n", CommonUtils.Nvl(this.getDelete1(), "")));
        stringBuilder.append(String.format("<I_BUDAT>%s</I_BUDAT>\n", CommonUtils.Nvl(this.getiBudate(), "")));
        stringBuilder.append("<ERPADD>\n");
        stringBuilder.append(String.format("<ADDIT1>%s</ADDIT1>\n", CommonUtils.Nvl(this.getAttribute1(), "")));
        stringBuilder.append(String.format("<ADDIT2>%s</ADDIT2>\n", CommonUtils.Nvl(this.getAttribute2(), "")));
        stringBuilder.append(String.format("<ADDIT3>%s</ADDIT3>\n", CommonUtils.Nvl(this.getAttribute3(), "")));
        stringBuilder.append(String.format("<ADDIT4>%s</ADDIT4>\n", CommonUtils.Nvl(this.getAttribute4(), "")));
        stringBuilder.append(String.format("<ADDIT5>%s</ADDIT5>\n", CommonUtils.Nvl(this.getAttribute5(), "")));
        stringBuilder.append("</ERPADD>\n");
        stringBuilder.append("</T_DELIVERY>\n");
        return stringBuilder.toString();
    }

2.创建接口返回类:

public class ItfDeliveryInformIfaceDtoVO {
    private String eType;
    private String eMsge;
    private String uuid;
    private String instructionNum;
    private List<ItfDeliveryInformVO> tDeliveryRet;//<T_DELIVERY_RET>
}
public class ItfDeliveryInformVO {
    private String traor;
    private String serno;
    private String vbeln;
    private String posnr;
    private String charg;
}

 说明:

VO类中的属性为接口响应参数XML格式的各节点名称,集合名为父节点,集合对象属性为父节点下的子节点名

3.编写httpClient工具类:

public class HttpUrlConnectionUtil {
    private Logger logger = LoggerFactory.getLogger(HttpUrlConnectionUtil.class);

 public String httpClientPost(String paramUrl, String params) throws Exception {
        // 生成输入流
        InputStream ins = null;
        Properties p = new Properties();
        try {
            ins = Resources.getResourceAsStream("config.properties");
            p.load(ins);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String username = p.getProperty("jco.client.user");
        String password = p.getProperty("jco.client.passwd");
        // 创建HttpClient
        HttpClient httpClient = new HttpClient();
        // 构造HttpClient的实例
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        PostMethod postMethod = new PostMethod(paramUrl);
        //使用系统提供的默认的恢复策略
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        StringRequestEntity requestEntity = new StringRequestEntity(params, "text/xml; charset=utf-8", "UTF-8");
        postMethod.setRequestEntity(requestEntity);
        httpClient.executeMethod(postMethod);
        // 读取内容
        return postMethod.getResponseBodyAsString();
    }
}

4.编写接口和实现类:

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public ItfDeliveryInformIfaceDtoVO DeliveryInformMesToSap(IRequest iRequest, List<EmtDeliveryInformIface> dtos) {

        ItfDeliveryInformIfaceDtoVO returnDtoVO = new ItfDeliveryInformIfaceDtoVO();
        //接口表插入
        self().insertDeliveryInformIface(iRequest, dtos);
        XmlUtil.Result result = new XmlUtil.Result();
        result.setSuccess(true);
        //获取接口地址 
        String url = "接口地址";
        //将数据整理成xml报文格式
        String uuid = StringHelper.getUUID();
        String param = setXML(dtos, uuid);//将接口数据拼成xml格式
        //发送请求 推送数据
        HttpUrlConnectionUtil util = new HttpUrlConnectionUtil();
        String returnMsg = "";
        List<ItfDeliveryInformVO> itfDeliveryInformVOList = new ArrayList<>();
        try {
            returnMsg = util.httpClientPost(url, param);
            result = XmlUtil.getSyncResult(returnMsg);//解析xml结果
            if (result.isSuccess()) {
                //获取返回结果对象
                returnDtoVO = XmlUtil.xmlStringToDto(ItfDeliveryInformIfaceDtoVO.class, "emt.itf.ws.erp_interface.delivery_inform.view.ItfDeliveryInformVO", returnMsg);//将返回结果解析为对象
                returnDtoVO.setUuid(uuid);
                itfDeliveryInformVOList = returnDtoVO.gettDeliveryRet();
            }
        } catch (Exception e) {
            e.printStackTrace();
            String message = XmlUtil.getErrMsg(e.getMessage() == null ? e.toString() : e.getMessage());
            result.setSuccess(false);
            result.setMsg(message);
            result.setSign("E");
            returnDtoVO.seteType("E");
            hapInterfaceOutbound.setStackTrace(Arrays.toString(e.getStackTrace()));
        }
        String status = result.getSign();
        String msg = result.getMsg();
        if (result.isSuccess()) {//更改接口表状态
            for (int i = 0; i < dtos.size(); i++) {
                if (dtos.get(i).getSyncCount() == null) {
                    dtos.get(i).setSyncCount(0d);
                }
                dtos.get(i).setStatus(status);
                dtos.get(i).setMessage(msg);
                dtos.get(i).setSyncCount(dtos.get(i).getSyncCount() + 1);
                dtos.get(i).setSyncTime(new Date());
                dtos.get(i).setUuid(uuid);
                self().updateByPrimaryKeySelective(iRequest, dtos.get(i));
            }
        } else {//更改接口表状态
            dtos.forEach(t -> {
                if (t.getSyncCount() == null) {
                    t.setSyncCount(0d);
                }
                t.setStatus(status);
                t.setMessage(msg);
                t.setSyncCount(t.getSyncCount() + 1);
                t.setSyncTime(new Date());
                t.setUuid(uuid);
                self().updateByPrimaryKeySelective(iRequest, t);
            });
            returnDtoVO.seteType(result.getSign());
            returnDtoVO.seteMsge(result.getMsg());
        }
        return returnDtoVO;
    }
    private String setXML(List<EmtDeliveryInformIface> list, String uuid) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:del=\"http://emtco.cn/HCM/ERP/DELIVERY_CREATE\">\n");
        stringBuilder.append("<soapenv:Header/>\n");
        stringBuilder.append("<soapenv:Body>\n");
        stringBuilder.append(" <del:MT_ERP_IN_DNCREATE>\n");
        stringBuilder.append(XmlUtil.getControlInfo("MES", "ERP", "ZSD003", DateUtils.toDateStr(new Date(), "yyyyMMddHHmmss"), uuid));
        stringBuilder.append(prepareData(list));
        stringBuilder.append(" </del:MT_ERP_IN_DNCREATE>\n");
        stringBuilder.append("</soapenv:Body>\n");
        stringBuilder.append("</soapenv:Envelope>");
        return stringBuilder.toString();
    }
    private String prepareData(List<EmtDeliveryInformIface> list) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<Data>\n");
        for (EmtDeliveryInformIface dto : list) {
            stringBuilder.append(dto.toString());
        }
        stringBuilder.append("</Data>\n");
        return stringBuilder.toString();
    }

 三,调用SRM系统提供的rest接口

1. 新建dto和接口返回dto类,此过程省略...(根据具体的接口参数定义)

2.编写获取token的工具类:

public class SrmItfUtils {
    private static final Logger logger = LoggerFactory.getLogger(SrmItfUtils.class);
    //oauth2.0认证信息参数 改到从配置中获取
/*    private final static String CLIENT_ID = "srm-interface-client";
    private final static String CLIENT_SECRET = "secret";
    private final static String GRANT_TYPE = "client_credentials";
    private final static String SCOPE = "default";*/
    //srm oauth2.0认证接口地址 改到从配置中获取
    //private final static String TOKEN_URL = "http://gateway.dev.isrm.going-link.com/oauth/oauth/token";

    static class TokenEntity {
        private String grant_type;
        private String client_id;
        private String client_secret;
        private String access_token;
        private String refresh_token;
        private String token_type;
        private String expires_in;
        private String scope;
    }

    public static String getAccessToken() throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        // 生成输入流
        InputStream ins = null;
        Properties p = new Properties();
        try {
            ins = Resources.getResourceAsStream("config.properties");
            p.load(ins);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String clientId = p.getProperty("oauth.client.id");
        String clientSecret = p.getProperty("oauth.client.secret");
        String grantType = p.getProperty("oauth.grant.type");
        String scope = p.getProperty("oauth.scope");
        String tokenUrl = p.getProperty("oauth.token.url");
        map.add("client_id", clientId);
        map.add("client_secret", clientSecret);
        map.add("grant_type", grantType);
        map.add("scope", scope);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(tokenUrl, request, String.class);
            if (HttpStatus.OK.equals(response.getStatusCode())) {
                TokenEntity responseEntity = JSON.parseObject(response.getBody(), TokenEntity.class);
                Assert.notNull(responseEntity, "Token entity is null!");
                return responseEntity.getAccess_token();
            } else {
                throw new Exception("HTTP StatusCode:" + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new Exception("get token error!");
        }
    }

}

3.编写接口和实现类:

    @Override
    public SrmReturnDto inspectionMesToSrm(InspectionDto dto) throws Exception {
        //获取iRequest对象
        IRequest iRequest = ItfCommonHelper.GetCustomIRequest();
        SrmReturnDto srmReturnDto = new SrmReturnDto();
        String url = "具体的接口地址;
        JSONObject json = JSONObject.fromObject(dto);
        String sendData = json.toString();
        //获取Token
        String accessToken = SrmItfUtils.getAccessToken();
        //程序设置超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(300000);// 设置建立连接超时时间
        requestFactory.setReadTimeout(300000);// 设置等待返回超时
        //开始请求
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        httpHeaders.add("Authorization", accessToken);
        ResponseEntity<T> responseEntity = null;
        try {
            HttpEntity<Object> requestEntity = new HttpEntity<>(sendData, httpHeaders);
            responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<String>() {
            }, Collections.EMPTY_MAP);
            String body = String.valueOf(responseEntity.getBody());
            //json转对象过程中,对象中有集合时会把集合的类型变成 MorphDynaBean 通过下面的方式解决:
            JsonConfig config = new JsonConfig();
            config.setRootClass(SrmReturnDto.class);
            Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
            classMap.put("restResponseDtlDTOList", RestResponseDtlDTO.class);
            config.setClassMap(classMap);
            srmReturnDto = (SrmReturnDto) JSONObject.toBean(JSONObject.fromObject(body), config);
            //srmReturnDto = (SrmReturnDto) ConvertUtils.JsonStrToDto(body, SrmReturnDto.class);
            logger.info(String.format("结果 >>> %s ...", responseEntity));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
      
        //接口传输成功更改接口表状态
        if ("SUCCESS".equals(srmReturnDto.getResponseStatus())) {
           
            }
        } else if ("ERROR".equals(srmReturnDto.getResponseStatus())) {
           
        }
        return srmReturnDto;
    }

四,接口调试工具

 推荐使用soapUI进行接口调试

打开软件选择:File->New Soap Project

 

 输入参数即可测试:(调用时传参也是根据此格式进行传输)

 

 

 


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Apache CXF是一个开源的WebService框架,可以帮助用户快速、简便地开发和部署WebService应用程序。它提供了多种方式来调用WebService接口,下面介绍几种常用的方式: 1. 使用JAX-WS API:CXF实现了JAX-WS API,可以直接使用JAX-WS提供的API来调用WebService。示例代码如下: ```java HelloWorldService service = new HelloWorldService(); HelloWorld port = service.getHelloWorldPort(); String result = port.sayHello("CXF"); ``` 2. 使用代理方式:CXF可以根据WebService WSDL文件自动生成代理类,然后通过调用代理类的方法来调用WebService接口。示例代码如下: ```java JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(HelloWorld.class); factory.setAddress("http://localhost:8080/HelloWorld"); HelloWorld client = (HelloWorld) factory.create(); String result = client.sayHello("CXF"); ``` 3. 使用Spring配置文件:CXF提供了Spring配置文件方式来实现WebService接口调用。用户可以在Spring配置文件中配置WebService客户端,然后通过Spring容器来获取WebService客户端实例。示例代码如下: ```xml <jaxws:client id="helloClient" serviceClass="com.example.HelloWorld" address="http://localhost:8080/HelloWorld"/> ``` ```java ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); HelloWorld client = (HelloWorld) context.getBean("helloClient"); String result = client.sayHello("CXF"); ``` 以上是几种常用的调用WebService接口的方式,可以根据具体情况选择适合自己的方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大王叫我来打死程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值