pzxsheng

          有種相見不敢見的傷痛,有種愛還埋藏在心中

          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;  
              } 
              

          posted on 2013-02-19 16:58 科菱財神 閱讀(18210) 評論(0)  編輯  收藏 所屬分類: Webservice

          導航

          <2013年2月>
          272829303112
          3456789
          10111213141516
          17181920212223
          242526272812
          3456789

          統計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 板桥市| 平阴县| 年辖:市辖区| 鄂尔多斯市| 上蔡县| 大同市| 栖霞市| 黔江区| 长宁县| 台湾省| 方山县| 岱山县| 正蓝旗| 瑞安市| 辽源市| 革吉县| 镇坪县| 都江堰市| 岑溪市| 清丰县| 鞍山市| 小金县| 鱼台县| 台北县| 通山县| 尚义县| 阳新县| 上饶县| 越西县| 张家口市| 长武县| 正蓝旗| 高安市| 威远县| 南和县| 扎赉特旗| 祁门县| 横峰县| 东乡县| 乌兰察布市| 云南省|