zoukankan      html  css  js  c++  java
  • iphone ios 用xcode4.2开发 访问web service的功能

    http://blog.csdn.net/panyaorui/article/details/8622990

    1。后台利用 cxf 构建一个web service服务。

    • HelloWorld.java
    [java] view plaincopy
     
     
    1. /** 
    2.  *  
    3.  */  
    4. package com.alcor.jws.test;  
    5.   
    6. import javax.jws.WebMethod;  
    7. import javax.jws.WebService;  
    8.   
    9. import org.apache.cxf.feature.Features;  
    10.   
    11. /** 
    12.  * @author 徐泽宇(roamer) 
    13.  *  
    14.  *         2010-7-10 
    15.  */  
    16. @WebService  
    17. @Features(features = "org.apache.cxf.feature.LoggingFeature")  
    18. public interface HelloWorld {  
    19.   
    20.     @WebMethod   
    21.     String sayHi(String text);  
    22.     @WebMethod   
    23.       
    24.     boolean userLogon(String username,String userpasswd);  
    25. }  
    • HelloWorldImpl.java
    [java] view plaincopy
     
     
    1. /** 
    2.  *  
    3.  */  
    4. package com.alcor.jws.test;  
    5.   
    6. import org.apache.cxf.feature.Features;  
    7. import org.apache.log4j.Logger;  
    8.   
    9. import javax.jws.WebMethod;  
    10. import javax.jws.WebService;  
    11.   
    12.   
    13. /** 
    14.  * @author 徐泽宇(roamer) 
    15.  * 
    16.  * 2010-7-10 
    17.  */  
    18. @WebService  
    19. @Features(features = "org.apache.cxf.feature.LoggingFeature")  
    20. public class HelloWorldImpl implements HelloWorld {  
    21.     /** 
    22.      * Logger for this class 
    23.      */  
    24.     private static final Logger logger = Logger.getLogger(HelloWorldImpl.class);  
    25.       
    26.       
    27.         @WebMethod   
    28.         public String sayHi(String text) {  
    29.         if (logger.isDebugEnabled()) {  
    30.             logger.debug("sayHi(String) - start"); //$NON-NLS-1$  
    31.         }  
    32.   
    33.         String returnString = "Hello,你好: " + text;  
    34.         if (logger.isDebugEnabled()) {  
    35.             logger.debug("返回内容:"+returnString);  
    36.             logger.debug("sayHi(String) - end"); //$NON-NLS-1$  
    37.         }  
    38.             return returnString;  
    39.         }  
    40.           
    41.         @WebMethod  
    42.         public boolean userLogon(String username ,String userpasswd)  
    43.         {  
    44.             logger.debug("用户名是:"+username+"口令是:"+userpasswd);  
    45.             if (username.equalsIgnoreCase("admin"))  
    46.             {  
    47.                 return true;  
    48.             }else{  
    49.                 return false;  
    50.             }  
    51.         }  
    52. }  
    • java 的web service 访问客户端
    [cpp] view plaincopy
     
     
    1. /** 
    2.  *  
    3.  */  
    4. package com.alcor.jws.test;  
    5.   
    6. import org.apache.cxf.interceptor.LoggingInInterceptor;  
    7. import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;  
    8.   
    9. /** 
    10.  * @author 徐泽宇(roamer) 
    11.  *  
    12.  *         2010-7-10 
    13.  */  
    14. public class Client {  
    15.   
    16.     private Client() {  
    17.     }  
    18.   
    19.     public static void main(String args[]) throws Exception {  
    20.         /*第一种方法,通过配置文件来实现  begin 
    21.         ApplicationContext ctx = new ClassPathXmlApplicationContext(    "META-INF/WebServiceClient.xml"); 
    22.          
    23.         HelloWorld client = (HelloWorld) ctx.getBean("client"); 
    24.  
    25.         String result = client.sayHi("Roamer"); 
    26.         System.out.println(result); 
    27.          
    28.         boolean logonResult = client.userLogon("roamer", "passwd"); 
    29.         System.out.println(logonResult); 
    30.          
    31.         logonResult = client.userLogon("admin", "passwd"); 
    32.         System.out.println(logonResult); 
    33.         */  
    34.           
    35.         JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();   
    36.         factory.setAddress("http://localhost:8080/SampleWebService/webservice/HelloWorld");   
    37.         factory.setServiceClass(HelloWorld.class);   
    38.         factory.getInInterceptors().add(new LoggingInInterceptor());   
    39.         HelloWorld helloWorld = (HelloWorld) factory.create();   
    40.         boolean msg = helloWorld.userLogon("admin","World");   
    41.         System.out.println(msg);   
    42.     }  
    43. }  


    2。iphone 客户端的编程

    • LogonViewController.h
    [cpp] view plaincopy
     
     
    1. //  
    2. //  LogonViewController.h  
    3. //  IManager  
    4. //  
    5. //  Created by remote roamer on 11-11-22.  
    6. //  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.  
    7. //  
    8.   
    9. #import <UIKit/UIKit.h>  
    10.   
    11.   
    12. @interface LogonViewController : UIViewController<NSXMLParserDelegate>  
    13. {  
    14.     IBOutlet UITextField * userNameTextField;  
    15.     IBOutlet UITextField * userPasswordTextField;  
    16.     IBOutlet UIButton    * userLogonButton;  
    17.     IBOutlet UITextField * webServiceURL;  
    18.     NSXMLParser *xmlParser;  
    19.     BOOL logonResult;  
    20.     NSMutableString *soapResults;  
    21. }  
    22.   
    23. @property(nonatomic,retain) IBOutlet UITextField * userNameTextField;  
    24. @property(nonatomic,retain) IBOutlet UITextField * userPasswordTextField;  
    25. @property(nonatomic,retain) IBOutlet UIButton    * userLogonButton;  
    26. @property(nonatomic,retain) IBOutlet UITextField * webServiceURL;  
    27. @property(nonatomic, retain) NSXMLParser *xmlParser;  
    28. @property(nonatomic,retain) NSMutableString * soapResults;  
    29.   
    30. -(IBAction) logonButtonClick:(id)sender;  
    31. @end  
    • LogonViewController.m
      [cpp] view plaincopy
       
       
      1. //  
      2. //  LogonViewController.m  
      3. //  IManager  
      4. //  
      5. //  Created by remote roamer on 11-11-22.  
      6. //  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.  
      7. //  
      8.   
      9. #import "LogonViewController.h"  
      10.   
      11.   
      12. @implementation LogonViewController  
      13.   
      14. @synthesize userNameTextField;  
      15. @synthesize userPasswordTextField;  
      16. @synthesize userLogonButton;  
      17. @synthesize webServiceURL;  
      18. @synthesize xmlParser;  
      19. @synthesize soapResults;  
      20.   
      21.   
      22. -(IBAction) logonButtonClick:(id)sender  
      23. {  
      24.     logonResult = false;  
      25.     NSString *soapMessage = [NSString stringWithFormat:  
      26.                              @"<?xml version="1.0" encoding="utf-8"?> "  
      27.                              "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"  
      28.                              "<soap:Body> "  
      29.                              "<ns1:userLogon xmlns:ns1="http://localhost:8080/SampleWebService/webservice/HelloWorld/">"  
      30.                              "<arg0>%@</arg0>"  
      31.                              "<arg1>%@</arg1>"  
      32.                              "</ns1:userLogon>"  
      33.                              "</soap:Body> "  
      34.                              "</soap:Envelope>",self.userNameTextField.text,self.userPasswordTextField.text];  
      35.     NSLog(@"调用webserivce的字符串是:%@",soapMessage);  
      36.     //请求发送到的路径  
      37.     NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];  
      38.     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/SampleWebService/webservice/HelloWorld/"];  
      39.     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];  
      40.       
      41.      //以下对请求信息添加属性前四句是必有的,  
      42.     [urlRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];  
      43.     [urlRequest addValue: @"http://localhost:8080/SampleWebService/webservice/HelloWorld" forHTTPHeaderField:@"SOAPAction"];  
      44.     [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];  
      45.     [urlRequest setHTTPMethod:@"POST"];  
      46.     [urlRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];  
      47.       
      48.   
      49.     //请求  
      50.     NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];  
      51.     theConnection = nil;  
      52.          
      53. }  
      54.   
      55. //如果调用有错误,则出现此信息  
      56. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  
      57. {  
      58.     NSLog(@"ERROR with theConenction");  
      59.     UIAlertView * alert =  
      60.         [[UIAlertView alloc]  
      61.              initWithTitle:@"提示"  
      62.              message:[error description]  
      63.              delegate:self  
      64.              cancelButtonTitle:nil  
      65.              otherButtonTitles:@"OK", nil];   
      66.     [alert show];  
      67. }  
      68.   
      69. //调用成功,获得soap信息  
      70. -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)responseData  
      71. {  
      72.     NSString * returnSoapXML = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];  
      73.     NSLog(@"返回的soap信息是:%@",returnSoapXML);  
      74.     //开始解析xml  
      75.     xmlParser = [[NSXMLParser alloc] initWithData: responseData];  
      76.     [xmlParser setDelegate:self];  
      77.     [xmlParser setShouldResolveExternalEntities: YES];  
      78.     [xmlParser parse];  
      79.     if(logonResult){  
      80.         UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"登录成功" message:returnSoapXML delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];  
      81.         [alert show];  
      82.     }  
      83.      
      84. }  
      85.   
      86. //如果soap的返回字符串比较多。需要实现以下这个方法,配合 didReceiveData 方法来正确的接受到所有的soap字符串  
      87. //原因是:如果soap的返回字符串比较多。didReceiveData 这个方法会多次被调用。如果把soap解析的功能直接写在didReceiveData这个方法里面。会出现错误。这个时候,就需要 和connectionDidFinishLoading 联用。实现思路是:定义一个类变量NSMutableString * returnSoapXML;用于存放返回的soap字符串。  
      88. //一旦有返回内容,获得soap信息,追加到结果字符串中  
      89. //-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)responseData  
      90. //{  
      91. //    [returnSoapXML appendString:[[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]];  
      92. //}  
      93. //最后在connectionDidFinishLoading 方法中实现,对完整的soap字符串的业务处理  
      94.   
      95. //数据全部接受成功以后调用  
      96. /* 
      97. - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
      98.     NSLog(@"从远程ws中调用获得客户简单信息的调用成功!");     
      99.     NSLog(@"返回的soap信息是:%@",returnSoapXML); 
      100.     //从soap 信息中解析出CusotmerInfo对象数组,并且保存到数据库中 
      101.     NSLog(@"开始保存ws返回的内容到本地数据库"); 
      102.     [[[SoapRtnJsonParser alloc] init] parse2CustomersInfo:[returnSoapXML dataUsingEncoding:NSUTF8StringEncoding]]; 
      103. */  
      104.   
      105. -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string  
      106. {  
      107.       
      108.     NSLog(@"返回的soap内容中,return值是: %@",string);  
      109.     if ([string isEqualToString:@"true"])  
      110.     {  
      111.         logonResult = YES;  
      112.     }else{  
      113.         logonResult = NO;  
      114.     }  
      115. }  
      116.   
      117.   
      118.   
      119.   
      120.   
      121. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
      122. {  
      123.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
      124.     if (self) {  
      125.         // Custom initialization  
      126.     }  
      127.     return self;  
      128. }  
      129.   
      130. - (void)didReceiveMemoryWarning  
      131. {  
      132.     // Releases the view if it doesn't have a superview.  
      133.     [super didReceiveMemoryWarning];  
      134.       
      135.     // Release any cached data, images, etc that aren't in use.  
      136. }  
      137.   
      138. #pragma mark - View lifecycle  
      139.   
      140. - (void)viewDidLoad  
      141. {  
      142.     [super viewDidLoad];  
      143.     // Do any additional setup after loading the view from its nib.  
      144. }  
      145.   
      146. - (void)viewDidUnload  
      147. {  
      148.     [super viewDidUnload];  
      149.     // Release any retained subviews of the main view.  
      150.     // e.g. self.myOutlet = nil;  
      151. }  
      152.   
      153. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
      154. {  
      155.     // Return YES for supported orientations  
      156.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
      157. }  
      158.   
      159. @end  

    相关文章 :

    其中要注意的几点。

    • [cpp] view plaincopy
       
       
      1. <ns1:userLogon xmlns:ns1="http://localhost:8080/SampleWebService/webservice/HelloWorld/">"  
      2.                              "<arg0>%@</arg0>"  
      3.                              "<arg1>%@</arg1>"  
      4.                              "</ns1:userLogon>"  

      中web service 中的 userLogon方法的调用 要用ns1来引用。
    • 传递的参数 不能和 webservice的变量名来写。而只能写成 arg0 和 arg1 这种方式。我查阅其他网上资料,都是写成<username>和<userpasswd>这种element的形式。但是在我的这个演示中,如果写成这种方式。后台会无法获得传入的变量。而用arg0 这种方式是可以传入。我不清楚是否是和 java cxf的webservice搭建环境和版本有关。

    注意:如果后台的WebService是.net开发的,调用的程序略有不同:

    例如 后台的ws服务链接是 :http://10.100.111.231:9000/MobileService.asmx

    那么访问这个url,会返回如下内容:

    这个页面提示了SOAP 1.1 和 SOAP 1.2 的调用的内容

    [html] view plaincopy
     
     
    1. SOAP 1.1  
    2.   
    3. The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values.  
    4.   
    5.  POST /MobileService.asmx HTTP/1.1  
    6. Host: 10.100.111.231  
    7. Content-Type: text/xml; charset=utf-8  
    8. Content-Length: length  
    9. SOAPAction: "http://tempuri.org/Logon"  
    10.   
    11. <?xml version="1.0" encoding="utf-8"?>  
    12. <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  
    13.   <soap:Body>  
    14.     <Logon xmlns="http://tempuri.org/">  
    15.       <userName>string</userName>  
    16.       <password>string</password>  
    17.     </Logon>  
    18.   </soap:Body>  
    19. </soap:Envelope>  
    20.   
    21. HTTP/1.1 200 OK  
    22. Content-Type: text/xml; charset=utf-8  
    23. Content-Length: length  
    24.   
    25. <?xml version="1.0" encoding="utf-8"?>  
    26. <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  
    27.   <soap:Body>  
    28.     <LogonResponse xmlns="http://tempuri.org/">  
    29.       <LogonResult>string</LogonResult>  
    30.     </LogonResponse>  
    31.   </soap:Body>  
    32. </soap:Envelope>  
    33.   
    34. SOAP 1.2  
    35.   
    36. The following is a sample SOAP 1.2 request and response. The placeholders shown need to be replaced with actual values.  
    37.   
    38. POST /MobileService.asmx HTTP/1.1  
    39. Host: 10.100.111.231  
    40. Content-Type: application/soap+xml; charset=utf-8  
    41. Content-Length: length  
    42.   
    43. <?xml version="1.0" encoding="utf-8"?>  
    44. <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">  
    45.   <soap12:Body>  
    46.     <Logon xmlns="http://tempuri.org/">  
    47.       <userName>string</userName>  
    48.       <password>string</password>  
    49.     </Logon>  
    50.   </soap12:Body>  
    51. </soap12:Envelope>  
    52.   
    53. HTTP/1.1 200 OK  
    54. Content-Type: application/soap+xml; charset=utf-8  
    55. Content-Length: length  
    56.   
    57. <?xml version="1.0" encoding="utf-8"?>  
    58. <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">  
    59.   <soap12:Body>  
    60.     <LogonResponse xmlns="http://tempuri.org/">  
    61.       <LogonResult>string</LogonResult>  
    62.     </LogonResponse>  
    63.   </soap12:Body>  
    64. </soap12:Envelope>  



    那么,我们在objectiveC中代码应该写成

       static NSString * wsURL = @"http://10.100.111.231:9000/MobileService.asmx";

       NSString *soapMessage = [NSString stringWithFormat:
                                 @"<?xml version="1.0" encoding="utf-8"?> "
                                 "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"
                                 "<soap:Body> "
                                 "<Logon xmlns="http://tempuri.org/">"
                                 "<userName>%@</userName>"
                                 "<password>%@</password>"
                                 "</Logon>"
                                 "</soap:Body> "
                                 "</soap:Envelope>",self.userNameTextField.text,self.userPasswordTextField.text];
        
        NSLog(@"调用webserivce的字符串是:%@",soapMessage);
        //请求发送到的路径
        NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",wsURL]];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
        
         //以下对请求信息添加属性前四句是必有的,
        [urlRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [urlRequest addValue:@"http://tempuri.org/Logon" forHTTPHeaderField:@"SOAPAction"];
        NSLog(@"SOAPAction is %@ ",@"http://tempuri.org/Logon");
        [urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
        [urlRequest setHTTPMethod:@"POST"];
        [urlRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
        

        //请求
        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
        theConnection = nil;

    注意红色的代码,这个http://tempurl.org/Logon 是要和 .net中的代码一致。否则无法访问。

  • 相关阅读:
    根据第三方提供的wsdl报文(axis2开发),进行的webservice应用的开发实例
    调用axis2开发的接口遇到的问题
    使用 DJ Java Decompiler 将整个jar包反编译成源文件
    解析Myeclipse项目下的.classpath文件
    使用cxf开发webservice应用时抛出异常
    hibernate 映射 多对一
    jquery获取元素的值,获取当前对象的父对象等等
    web项目中加入struts2、spring的支持,并整合两者
    Struts2中的 配置文件
    对list集合中的对象按照对象的某一属性进行排序
  • 原文地址:https://www.cnblogs.com/NSNULL/p/4397526.html
Copyright © 2011-2022 走看看