iphone ios 用xcode4.2开发 访问web service的功能

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

  • HelloWorld.java
[java]  view plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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 plain copy
    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\"?>\n"  
    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>\n"  
    29.                              "<ns1:userLogon xmlns:ns1=\"http://localhost:8080/SampleWebService/webservice/HelloWorld/\">"  
    30.                              "<arg0>%@</arg0>"  
    31.                              "<arg1>%@</arg1>"  
    32.                              "</ns1:userLogon>"  
    33.                              "</soap:Body>\n"  
    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. { 
    99.     NSLog(@"从远程ws中调用获得客户简单信息的调用成功!");     
    100.     NSLog(@"返回的soap信息是:%@",returnSoapXML); 
    101.     //从soap 信息中解析出CusotmerInfo对象数组,并且保存到数据库中 
    102.     NSLog(@"开始保存ws返回的内容到本地数据库"); 
    103.     [[[SoapRtnJsonParser alloc] init] parse2CustomersInfo:[returnSoapXML dataUsingEncoding:NSUTF8StringEncoding]]; 
    104. } 
    105. */  
    106.   
    107. -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string  
    108. {  
    109.       
    110.     NSLog(@"返回的soap内容中,return值是: %@",string);  
    111.     if ([string isEqualToString:@"true"])  
    112.     {  
    113.         logonResult = YES;  
    114.     }else{  
    115.         logonResult = NO;  
    116.     }  
    117. }  
    118.   
    119.   
    120.   
    121.   
    122.   
    123. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
    124. {  
    125.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
    126.     if (self) {  
    127.         // Custom initialization  
    128.     }  
    129.     return self;  
    130. }  
    131.   
    132. - (void)didReceiveMemoryWarning  
    133. {  
    134.     // Releases the view if it doesn't have a superview.  
    135.     [super didReceiveMemoryWarning];  
    136.       
    137.     // Release any cached data, images, etc that aren't in use.  
    138. }  
    139.   
    140. #pragma mark - View lifecycle  
    141.   
    142. - (void)viewDidLoad  
    143. {  
    144.     [super viewDidLoad];  
    145.     // Do any additional setup after loading the view from its nib.  
    146. }  
    147.   
    148. - (void)viewDidUnload  
    149. {  
    150.     [super viewDidUnload];  
    151.     // Release any retained subviews of the main view.  
    152.     // e.g. self.myOutlet = nil;  
    153. }  
    154.   
    155. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
    156. {  
    157.     // Return YES for supported orientations  
    158.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
    159. }  
    160.   
    161. @end  

相关文章 :

  • 手把手教你做 iphone的soap应用
  • 分享一个用Xcode4实现基于Webservice用户登录的iphone程序


其中要注意的几点。

  • [cpp]  view plain copy
    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 plain copy
  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\"?>\n"
                             "<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>\n"
                             "<Logon xmlns=\"http://tempuri.org/\">"
                             "<userName>%@</userName>"
                             "<password>%@</password>"
                             "</Logon>"
                             "</soap:Body>\n"
                             "</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中的代码一致。否则无法访问。

你可能感兴趣的:(iphone ios 用xcode4.2开发 访问web service的功能)