CXF 动态客户端

服务端:

第一步、定义接口

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface IUser {
    @WebMethod
    void addUser(UserDto userDto);
}
第二步、接口实现
 
public class UserImpl implements IUser {
    @Override
    public void addUser(UserDto userDto) {
        System.out.println("正在新增信息");
        System.out.println(new Gson().toJson(userDto));
    }
}
第三步、定义DTO
 
@XmlRootElement(name = "UserDto")
@XmlAccessorType(XmlAccessType.FIELD)
//@XmlType(namespace = "dto.inter.server.cxf.com") 定义DTO的nameSace,发布后的nameSpace和service一致 可以在此处更改
public class UserDto implements Serializable {
    private static final long serialVersionUID = -5691763516137528419L;

    private String id;

    private String name;

    private int age;

    private String mobile;

    private String addr;
           ……}
第四步、服务发布
 
//使用JaxWsServerFactoryBean发布服务,需要在类上加入@WebService注解,
//如果不加,当前类中的方法都不能被发布为web方法
JaxWsServerFactoryBean bean = new JaxWsServerFactoryBean();
//发布服务的地址
bean.setAddress("http://10.26.160.165:8080/user");
//接口类型
bean.setServiceClass(IUser.class);
//接口的实现类
bean.setServiceBean(new UserImpl());
//发布服务
bean.create();
客户端
public static void main(String[] args) throws Exception {
        Client userClient = getCxfClient("http://localhost:8080/user/UserService?wsdl");

        Object dataTypes = Thread.currentThread().getContextClassLoader().loadClass("com.cxf.server.inter.UserDto").newInstance();
        Method id = dataTypes.getClass().getMethod("setId", String.class);
        Method name = dataTypes.getClass().getMethod("setName", String.class);
        Method age = dataTypes.getClass().getMethod("setAge", int.class);
        Method mobile = dataTypes.getClass().getMethod("setMobile", String.class);
        Method addr = dataTypes.getClass().getMethod("setAddr", String.class);

        id.invoke(dataTypes, "0001");
        name.invoke(dataTypes, "UUU");
        age.invoke(dataTypes, 18);
        mobile.invoke(dataTypes, "110");
        addr.invoke(dataTypes, "杭州");
        Object result = userClient.invoke("addUser",dataTypes);
        System.out.println("喻攀大搓逼");
    }

public static Client getCxfClient(String wsdlUrl) {
    JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
    Client client = factory.createClient(wsdlUrl);
    HTTPConduit conduit = (HTTPConduit) client.getConduit();
    HTTPClientPolicy policy = new HTTPClientPolicy();
    String connectionTimeout = "2000";
    if (connectionTimeout != null && !"".equals(connectionTimeout)) {
        int conTimeout = Integer.parseInt(connectionTimeout);
        policy.setConnectionTimeout(conTimeout); //连接超时时间
    }
    //policy.setReceiveTimeout(120000);//请求超时时间.
    conduit.setClient(policy);
    return client;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值