首页>>iPhone >>开发
手把手教你做iphone的soap应用(webservice)
楼:1
九品仙
2011-6-1 12:20:12
手把手教你做iphone的soap应用(webservice)
http://www.cocoachina.com/bbs/read.php?tid-16561.html
最近研究了下soap,找不到iphone上好用的soap代码.发现坛子,关于soap的东西也不多,就把自己写的贴出来,请大家批评指正吧。

用到的提供soap接口的网址是:http://www.Nanonull.com/TimeService/这个页面有多个方法可以通过soap调用,页面上也有说明.如果用IE的浏览器还能看到此网页提供的wsdl文件.要做soap的webservice首先要了解一些关于webservice和soap的一些基本知识.下面几个网址可能会帮你快速入门.

soap教程:http://www.w3school.com.cn/soap/index.asp
使用WSDL发布WebService:http://blog.csdn.net/meiqingsong/archive/2005/04/04/336057.aspx

    为了便于理解,我先讲下soap的大体原理:我们在iphone封装soap请求信息,发送到某个提供soap服务的服务器,如下例中我们用到的http://www.Nanonull.com/TimeService/.服务器能接受和识别soap请求,当它接到请求,就根据客户端的请求情况调用服务器上的某个函数,并将函数返回结果封装成soap反馈信息发送给客户端.客户端接收到soap反馈信息后,进行解析处理,以用户能理解的形式呈现给用户.整个过程就这么简单.

    好了,假设现在你已经有关于soap的基础知识(没有也没关系,看了例子,再理解就更好理解了),下面我们开始做soap的例子.

    第一步,建一个Hello_SOAP项目.用IB将Hello_SOAPViewController.xib做成如下图的界面

然后在Hello_SOAPViewController.h中添加如下代码
复制代码
  1. @interface Hello_SOAPViewController : UIViewController
  2. {
  3.         IBOutlet UITextField *nameInput;
  4.         IBOutlet UILabel *greeting;

  5.         NSMutableData *webData;
  6.         NSMutableString *soapResults;
  7.         NSXMLParser *xmlParser;
  8.         BOOL recordResults;
  9. }

  10. @property(nonatomic, retain) IBOutlet UITextField *nameInput;
  11. @property(nonatomic, retain) IBOutlet UILabel *greeting;

  12. @property(nonatomic, retain) NSMutableData *webData;
  13. @property(nonatomic, retain) NSMutableString *soapResults;
  14. @property(nonatomic, retain) NSXMLParser *xmlParser;

  15. -(IBAction)buttonClick: (id) sender;
  16. - (void)getOffesetUTCTimeSOAP;

然后在Hello_SOAPViewController.xib中将两个输出口和一个动作连接好,这个不用手把手吧?
在Hello_SOAPViewController.m文件中加入以下方法 :
复制代码
  1. - (void)getOffesetUTCTimeSOAP
  2. {
  3.         recordResults = NO;
  4.         //封装soap请求消息
  5.         NSString *soapMessage = [NSString stringWithFormat:
  6.                                                          @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
  7.                                                          "<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/\">\n"
  8.                                                          "<soap:Body>\n"
  9.                                                          "<getOffesetUTCTime xmlns=\"http://www.Nanonull.com/TimeService/\">\n"
  10.                                                          "<hoursOffset>%@</hoursOffset>\n"
  11.                                                          "</getOffesetUTCTime>\n"
  12.                                                          "</soap:Body>\n"
  13.                                                          "</soap:Envelope>\n",nameInput.text
  14.                                                          ];
  15.         NSLog(soapMessage);
  16.         //请求发送到的路径
  17.         NSURL *url = [NSURL URLWithString:@"http://www.nanonull.com/TimeService/TimeService.asmx"];
  18.         NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
  19.         NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
  20.         
  21.         //以下对请求信息添加属性前四句是必有的,第五句是soap信息。
  22.         [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  23.         [theRequest addValue: @"http://www.Nanonull.com/TimeService/getOffesetUTCTime" forHTTPHeaderField:@"SOAPAction"];
  24.         
  25.         [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
  26.         [theRequest setHTTPMethod:@"POST"];
  27.         [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
  28.         
  29.         //请求
  30.         NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  31.         
  32.         //如果连接已经建好,则初始化data
  33.         if( theConnection )
  34.         {
  35.                 webData = [[NSMutableData data] retain];
  36.         }
  37.         else
  38.         {
  39.                 NSLog(@"theConnection is NULL");
  40.         }
  41.         
  42.         
  43. }

这个方法作用就是封装soap请求,并向服务器发送请求.
代码有注释.不重复讲解.soap并不难,难的是没有案例告诉我们怎么把其它平台的soap移植过来,这里我给出了代码,我相信对iphone开发人员的话应该能看懂了.我在下面会把此案例的源代码附上.如果自己做不出来再看我的代码.如果我这样讲您觉得不够细,那说明您的iphone开发还不是太深入,那么您应该用不到soap技术.可以飘过了.
下面的代码是接收信息并解析,显示到用户界面
复制代码
  1. -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  2. {
  3.         [webData setLength: 0];
  4.         NSLog(@"connection: didReceiveResponse:1");
  5. }
  6. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  7. {
  8.         [webData appendData:data];
  9.         NSLog(@"connection: didReceiveData:2");

  10. }

  11. //如果电脑没有连接网络,则出现此信息(不是网络服务器不通)
  12. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
  13. {
  14.         NSLog(@"ERROR with theConenction");
  15.         [connection release];
  16.         [webData release];
  17. }
  18. -(void)connectionDidFinishLoading:(NSURLConnection *)connection
  19. {
  20.         NSLog(@"3 DONE. Received Bytes: %d", [webData length]);
  21.         NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
  22.         NSLog(theXML);
  23.         [theXML release];
  24.         
  25.         //重新加載xmlParser
  26.         if( xmlParser )
  27.         {
  28.                 [xmlParser release];
  29.         }
  30.         
  31.         xmlParser = [[NSXMLParser alloc] initWithData: webData];
  32.         [xmlParser setDelegate: self];
  33.         [xmlParser setShouldResolveExternalEntities: YES];
  34.         [xmlParser parse];
  35.         
  36.         [connection release];
  37.         //[webData release];
  38. }

  39. -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
  40. attributes: (NSDictionary *)attributeDict
  41. {
  42.         NSLog(@"4 parser didStarElemen: namespaceURI: attributes:");

  43.                 if( [elementName isEqualToString:@"getOffesetUTCTimeResult"])
  44.         {
  45.                 if(!soapResults)
  46.                 {
  47.                         soapResults = [[NSMutableString alloc] init];
  48.                 }
  49.                 recordResults = YES;
  50.         }
  51.         
  52. }
  53. -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
  54. {
  55.         NSLog(@"5 parser: foundCharacters:");

  56.         if( recordResults )
  57.         {
  58.                 [soapResults appendString: string];
  59.         }
  60. }
  61. -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
  62. {
  63.         NSLog(@"6 parser: didEndElement:");

  64.         if( [elementName isEqualToString:@"getOffesetUTCTimeResult"])
  65.         {
  66.                 recordResults = FALSE;
  67.                 greeting.text = [[[NSString init]stringWithFormat:@"第%@时区的时间是: ",nameInput.text] stringByAppendingString:soapResults];
  68.                 [soapResults release];
  69.                 soapResults = nil;
  70.                 NSLog(@"hoursOffset result");
  71.         }
  72.         
  73. }
  74. - (void)parserDidStartDocument:(NSXMLParser *)parser{
  75.         NSLog(@"-------------------start--------------");
  76. }
  77. - (void)parserDidEndDocument:(NSXMLParser *)parser{
  78.         NSLog(@"-------------------end--------------");
  79. }

说明下:
复制代码
  1. -(void)connectionDidFinishLoading:(NSURLConnection *)connection


这个方法是存储接收到的信息
复制代码
  1. -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

方法是显示接收的信息.
以上代码已经包括所有用到的代码.
如果一切顺利,应该有如下界面
1.打开界面

2.输入请求的时区

3.显示服务器反馈结果

下面给个整个工程的源码,如果您把上面代码贴上运行不出来,直接运行我的工程吧.有误地方请指正,有问题可回帖交流.
Hello_SOAP-getOffesetUTCTime.zip (62 K) 下载次数:1485