在项目中用到了好多的调用WebSerViece的请求的地方,一直用系统的?NSMutableURLRequest 和NSURLConnection结合实现的,这样做有一定的好处,原生态,不会过时。
但是有时你获取需要实现一定的效果,用系统的虽然也能实现,但比较麻烦,除非自己封装,要不每次都的重写,ASI是比较好的网络请求开源框架,用的人比较多,遗憾的是已经停止更新,(据说在ios7 下有些问题,暂时还没有研究,等ios7正式发布以后在具体的试试),暂时还是能用的,这里就说说怎么用ASIHttpRequest 调用WebService
1、传统的调用方式(具体的你可以参考http://www.cocoachina.com/bbs/read.php?tid=16561&keyword=soap)
- - (void)getOffesetUTCTimeSOAP
- {
- ????????recordResults = NO;
- ????????//封装soap请求消息
- ????????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/">n"
- ???????????????????????????????????????????????????????? "<soap:Body>n"
- ???????????????????????????????????????????????????????? "<getOffesetUTCTime xmlns="http://www.Nanonull.com/TimeService/">n"
- ???????????????????????????????????????????????????????? "<hoursOffset>%@</hoursOffset>n"
- ???????????????????????????????????????????????????????? "</getOffesetUTCTime>n"
- ???????????????????????????????????????????????????????? "</soap:Body>n"
- ???????????????????????????????????????????????????????? "</soap:Envelope>n",nameInput.text
- ???????????????????????????????????????????????????????? ];
- ????????NSLog(soapMessage);
- ????????//请求发送到的路径
- ????????NSURL *url = [NSURL URLWithString:@"http://www.nanonull.com/TimeService/TimeService.asmx"];
- ????????NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
- ????????NSString *msgLength = [NSString stringWithFormat:@"%d",[soapMessage length]];
- ????????
- ????????//以下对请求信息添加属性前四句是必有的,第五句是soap信息。
- ????????[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
- ????????[theRequest addValue: @"http://www.Nanonull.com/TimeService/getOffesetUTCTime" forHTTPHeaderField:@"SOAPAction"];
- ????????[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
- ????????[theRequest setHTTPMethod:@"POST"];
- ????????[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
- ????????//请求
- ????????NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
- ????????//如果连接已经建好,则初始化data
- ????????if( theConnection )
- ????????{
- ????????????????webData = [[NSMutableData data] retain];
- ????????}
- ????????else
- ????????????????NSLog(@"theConnection is NULL");
- }
2 通过ASI调用webService 其实和传统的方式基本一样,只是做了相关的封装而已,具体的请参考下面的文章
http://www.cocoachina.com/bbs/read.php?tid=98388&keyword=http