server:
接口:
1 package com.mrlu.webService; 2 3 import javax.jws.WebParam; 4 import javax.jws.WebService; 5 6 /** 7 * Created by stefan on 16-1-11. 8 */ 9 @WebService 10 public interface IMyService { 11 public int add( 12 @WebParam(name = "value1")int a, 13 @WebParam(name = "value2")int b); 14 }
实现类:
1 package com.mrlu.webService.impl; 2 3 import com.mrlu.webService.IMyService; 4 5 import javax.jws.WebParam; 6 import javax.jws.WebService; 7 8 /** 9 * Created by stefan on 16-1-11. 10 */ 11 @WebService(endpointInterface = "com.mrlu.webService.IMyService") 12 public class MyServiceImpl implements IMyService { 13 14 @Override 15 public int add(@WebParam(name = "value1")int value1, 16 @WebParam(name = "value2")int value2) { 17 System.out.println(value1 + " " + value2); 18 try { 19 Thread.sleep(5000); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 return value1+value2; 24 } 25 }
启动服务器:
public class Main { public static void main(String[] args){ String address = "http://localhost:1234/service"; Endpoint.publish(address, new MyServiceImpl()); } }
生成client代码:
使用jdk自带的wsimport工具:
wsimport -d /user/webservice -keep -verbose "http://localhost:1234/service?wsdl"
将生成的代码拷贝到新项目里
client结构:
MyClient:
1 public class MyClient { 2 public static void main(String[] args){ 3 /* 方法一: 4 URL url = new URL("http://localhost:7777/tudou?wsdl"); 5 QName qName = new QName("http://impl.webService.mrlu.com/", "MyServiceImplService"); 6 Service service = Service.create(url, qName); 7 IMyService iMyService = service.getPort(IMyService.class); 8 System.out.println(iMyService.add(1,2)); 9 */ 10 11 //方法二: 12 MyServiceImplService myServiceImplService = new MyServiceImplService(); 13 Type[] interfaces = myServiceImplService.getMyServiceImplPort().getClass().getGenericInterfaces(); 14 for(Type interfacea: interfaces){ 15 System.out.println(interfacea); 16 } 17 IMyService iMyService = myServiceImplService.getMyServiceImplPort(); 18 //设置读取数据超时时间 19 ((BindingProvider)iMyService).getRequestContext().put(BindingProviderProperties.REQUEST_TIMEOUT, 6000); 20 //设置连接超时时间 21 ((BindingProvider)iMyService).getRequestContext().put(BindingProviderProperties.CONNECT_TIMEOUT, 1000); 22 System.out.println(iMyService.add(1,2)); 23 } 24 }
输出:
interface com.mrlu.webservice.impl.IMyService interface com.sun.xml.internal.ws.developer.WSBindingProvider interface com.sun.xml.internal.ws.Closeable 3
总结: client中生成的IMyService子类是一个代理类,此代理类同时实现了BindingProvider接口,通过此接口的方法可以获取requestContext, responseContext, Bind等,可以设置一些参数,如超时时间等