Java Webservice调用总结

Java Webservice调用总结

一、调用ASP.NET发布的WebService服务
以下是SOAP1.2请求事例
     POST /user/yfengine.asmx HTTP/1.1
    Host: oserver.palm-la.com
    Content-Type: application/soap+xml; charset=utf-8
    Content-Length: length
     <? xml version="1.0" encoding="utf-8" ?>
     < soap12:Envelope  xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd ="http://www.w3.org/2001/XMLSchema"  xmlns:soap12 ="http://www.w3.org/2003/05/soap-envelope" >
           < soap12:Body >
             < Login  xmlns ="Loginnames" >
                   < userId > string </ userId >
                   < password > string </ password >
             </ Login >
           </ soap12:Body >
     </ soap12:Envelope >
1、方式一:通过AXIS调用
String serviceEpr = "http://127.0.0.1/rightproject/WebServices/RightService.asmx";
public  String callWebServiceByAixs(String userId, String password, String serviceEpr){
              
         try  {
               Service service  =  new  Service();
               Call call  =  (Call)service.createCall();
               call.setTargetEndpointAddress( new  java.net.URL(serviceEpr));
                // 服务名
               call.setOperationName( new  QName( " http://tempuri.org/ " " Login " ));   
                // 定义入口参数和参数类型
               call.addParameter( new  QName( " http://tempuri.org/ " " userId " ),XMLType.XSD_STRING, ParameterMode.IN);
               call.addParameter( new  QName( " http://tempuri.org/ " " password " ),XMLType.XSD_STRING, ParameterMode.IN);
               call.setUseSOAPAction( true );
                // Action地址
               call.setSOAPActionURI( " http://tempuri.org/Login " );
                // 定义返回值类型
               call.setReturnType(XMLType.XSD_INT);
               
                // 调用服务获取返回值    
               String result  =  String.valueOf(call.invoke( new  Object[]{userId, password}));
               System.out.println( " 返回值 :  "  +  result);
                return  result;
              }  catch  (ServiceException e) {
               e.printStackTrace();
              }  catch  (RemoteException e) {
               e.printStackTrace();
              }  catch  (MalformedURLException e) {
               e.printStackTrace();
              }
        
         return  null ;
    }
2、方式二: 通过HttpClient调用webservice
soapRequest 为以下Xml,将请求的入口参数输入
<? xml version="1.0" encoding="utf-8" ?>
         < soap12:Envelope  xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd ="http://www.w3.org/2001/XMLSchema"  xmlns:soap12 ="http://www.w3.org/2003/05/soap-envelope" >
           < soap12:Body >
             < Login  xmlns ="Loginnames" >
                   < userId > 张氏 </ userId >
                   < password > 123456 </ password >
             </ Login >
           </ soap12:Body >
     </ soap12:Envelope >
String serviceEpr = "http://127.0.0.1/rightproject/WebServices/RightService.asmx";
String contentType = "application/soap+xml; charset=utf-8";
public  static  String callWebService(String soapRequest, String serviceEpr, String contentType){
        
        PostMethod postMethod  =  new  PostMethod(serviceEpr);
         // 设置POST方法请求超时
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,  5000 );
        
         try  {
            
             byte [] b  =  soapRequest.getBytes( " utf-8 " );
            InputStream inputStream  =  new  ByteArrayInputStream(b,  0 , b.length);
            RequestEntity re  =  new  InputStreamRequestEntity(inputStream, b.length, contentType);
            postMethod.setRequestEntity(re);
            
            HttpClient httpClient  =  new  HttpClient();
            HttpConnectionManagerParams managerParams  =  httpClient.getHttpConnectionManager().getParams(); 
             //  设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout( 30000 );
             //  设置读数据超时时间(单位毫秒)
            managerParams.setSoTimeout( 600000 ); 
             int  statusCode  =  httpClient.executeMethod(postMethod);
             if  (statusCode  !=  HttpStatus.SC_OK)  
                 throw  new  IllegalStateException( " 调用webservice错误 :  "  +  postMethod.getStatusLine()); 
            
            String soapRequestData  =   postMethod.getResponseBodyAsString();
            inputStream.close();
             return  soapRequestData;
        }  catch  (UnsupportedEncodingException e) {
             return  " errorMessage :  "  +  e.getMessage();
        }  catch  (HttpException e) {
             return  " errorMessage :  "  +  e.getMessage();
        }  catch  (IOException e) {
             return  " errorMessage :  "  +  e.getMessage();
        } finally {
             postMethod.releaseConnection(); 
        }
    }

二、调用其他WebService服务
1、方式一:通过AIXS2调用
serviceEpr:服务地址
nameSpace:服务命名空间
methodName:服务名称
Object[] args = new Object[]{"请求的数据"};
DataHandler dataHandler = new DataHandler(new FileDataSource("文件路径"));
传文件的话,"请求的数据"可以用DataHandler对象,但是WebService服务需提供相应的处理即:
InputStream inputStream = DataHandler.getInputStream();
然后将inputStream写入文件即可。 还可以将文件读取为二进制流进行传递。
public  static  String callWebService(String serviceEpr, String nameSpace, Object[] args, String methodName){
         try {
        
            RPCServiceClient serviceClient  =  new  RPCServiceClient();
            Options options  =  serviceClient.getOptions();
            EndpointReference targetEPR  =  new  EndpointReference(serviceEpr);
            options.setTo(targetEPR);
            
             // ===========可以解决多次调用webservice后的连接超时异常========
            options.setManageSession( true );   
            options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, true );   
           
             // 设置超时
            options.setTimeOutInMilliSeconds( 60000L );
             //  设定操作的名称
            QName opQName  =  new  QName(nameSpace, methodName);
             //  设定返回值
            
//  操作需要传入的参数已经在参数中给定,这里直接传入方法中调用
            Class[] opReturnType  =  new  Class[] { String[]. class  };
             // 请求并得到返回值
            Object[] response  =  serviceClient.invokeBlocking(opQName, args, opReturnType);
            String sResult  =  ((String[]) response[ 0 ])[ 0 ];
             // ==========可以解决多次调用webservice后的连接超时异常=======
            serviceClient.cleanupTransport(); 
             return  sResult;
        
        } catch (AxisFault af){
             return  af.getMessage();
        }
    }
    
2、方式二:
serviceEpr:服务器地址
nameSpace:服务命名空间
methodName:服务名称
private  static  void  callWebService(String serviceEpr, String nameSpace, String methodName) {
         try  {
            EndpointReference endpointReference  =  new  EndpointReference(serviceEpr);
             //  创建一个OMFactory,下面的namespace、方法与参数均需由它创建
            OMFactory factory  =  OMAbstractFactory.getOMFactory();
             //  创建命名空间
            OMNamespace namespace  =  factory.createOMNamespace(nameSpace,  " urn " );
             //  参数对数
            OMElement nameElement  =  factory.createOMElement( " arg0 " null );
            nameElement.addChild(factory.createOMText(nameElement,  " 北京 " ));
             //  创建一个method对象
            OMElement method  =  factory.createOMElement(methodName, namespace);
            method.addChild(nameElement);
            Options options  =  new  Options();
             //  SOAPACTION
            
// options.setAction("sayHi");
            options.setTo(endpointReference);
            
            options.setSoapVersionURI(org.apache.axiom.soap.SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); 
            ServiceClient sender  =  new  ServiceClient();
            sender.setOptions(options);
             //  请求并得到结果
            OMElement result  =  sender.sendReceive(method);
            System.out.println(result.toString());
        }  catch  (AxisFault ex) {
            ex.printStackTrace();
        }
    }
    
3、方式三:通过CXF调用
serviceEpr:服务器地址
nameSpace:服务命名空间
methodName:服务名称
public  static  String callWebService(String serviceEpr, String nameSpace, String methodName){
        
        JaxWsDynamicClientFactory clientFactory  =  JaxWsDynamicClientFactory.newInstance();
        Client client  =  clientFactory.createClient(serviceEpr);
        Object[] resp  =  client.invoke(methodName,  new  Object[]{ " 请求的内容 " });
        System.out.println(resp[ 0 ]);
    }
    
     // 传文件,将文件读取为二进制流进行传递,“请求内容”则为二进制流
     private  byte [] getContent(String filePath)  throws  IOException{  
        
     FileInputStream inputStream  =  new  FileInputStream(filePath);    
     ByteArrayOutputStream outputStream  =  new  ByteArrayOutputStream( 1024 );  
         System.out.println( " bytes available:  "  +  inputStream.available());  
  
         byte [] b  =  new  byte [ 1024 ];        
         int  size  =  0 ;  
          
         while ((size  =  inputStream.read(b))  != - 1 )   
            outputStream.write(b,  0 , size);   
          
     inputStream.close();   
         byte [] bytes  =  outputStream.toByteArray();  
         outputStream .close();
 

         return  bytes;  
    } 
    

你可能感兴趣的:(Java Webservice调用总结)