流程:
1.新建一个java工程
2.建立WebService接口
3.接口的实现类
4.java客户端调用
5.C#端调用
下面开始:
所需的资料:
apache-cxf-2.7.5 下载链接 http://download.csdn.net/detail/surehao/7005281
找相应的jar,导入项目
建立WebService接口:
import javax.jws.WebService;
@WebService
public interface ServiceInterface {
public String hi(String hi);
}
接口的实现类:
package com.cxf.server;
package com.cxf.server;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService(endpointInterface="com.cxf.server.ServiceInterface",serviceName="hiService")
public class Server implements ServiceInterface {
@Override
public String hi(String hi) {
return hi+"你好";
}
/**
* @param args
*/
public static void main(String[] args) {
Server server=new Server();
String address="http://localhost:9009/hi";
Endpoint.publish(address, server);
}
}
java客户端调用
package com.cxf.client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class Client {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
org.apache.cxf.endpoint.Client client = dcf.createClient("http://localhost:9009/hi?wsdl");
Object[] objects=client.invoke("hi", "surehao");
System.out.println(objects[0].toString());
}
}
先运行接口的实现类Server,就可发布了一个WebService ,可访问http://localhost:9009/hi?wsdl看是否发布成功.
下面贴点问题:
javax.xml.stream.XMLStreamException: java.io.IOException: 您的主机中的软件放弃了一个已建立的连接。
org.apache.cxf.interceptor.Fault: Could not send Message
这两个错误是我在实际项目中发布时出现的,因为项目的数据访问过大,可能导致响应超时,连接中断等问题,可在客户端访问代码中加入以下代码:
HTTPConduit http = (HTTPConduit) client.getConduit();
http.getClient().setReceiveTimeout(0);
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(6000000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(6000000);
再去调用client.invoke()获取数据
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
C#访问上面发布的WebService
打开vs2010,新建一个控制台项目,点击项目名,右键--选择Add Service Reference ,把相应的http://localhost:9009/hi?wsdl添加到Address中,点击GO,这时会找到你发布的接口,选择它,点击OK,再通过以下代码就可调用接口
ServiceReference1.ServiceInterfaceClient client = new ServiceReference1.ServiceInterfaceClient();
Console.WriteLine(client.hi("surehao"));
项目Deom下载 http://download.csdn.net/detail/surehao/7005439
OK.........
本博客介绍了如何使用Apache CXF在Java中创建并发布一个WebService,以及如何从Java客户端和C#客户端进行调用。首先创建Java工程,定义WebService接口并实现,然后发布并验证接口。对于Java客户端,需处理可能出现的连接中断异常。对于C#客户端,通过VS2010添加服务引用并调用接口。

4004

被折叠的 条评论
为什么被折叠?



