IOS 之 网络通信Web Servic
来源:互联网 发布:和其正 知乎 编辑:程序博客网 时间:2024/06/07 07:24
Web Service使用的是HTTP协议,并使用URI来定位资源.数据交换格式使用的是JSON和XML等,所支持的方法包括POST,GET,PUT,DELETE等.
下面介绍一下这些IOS SDK通信类的使用方法:
同步GET通信方法:
-(void)startRequest{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp?email=%@&type=%@&action=%@", @"samrtian@xx.com", @"JSON", @"query"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:nil]; //线程处于一直等待中完成后开始执行下边 NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];}
//这是另一种初始化方法
- (id)initWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval
cachePolicy属性可以有以下几个定义
enum { NSURLRequestUseProtocolCachePolicy = 0, //默认的缓存策略,由协议定义
NSURLRequestReloadIgnoringLocalCacheData = 1, //忽略缓存直接从原始地址请求
NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4, //忽略本地和远程的缓存数据,直接从原始地址请求
NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,
NSURLRequestReturnCacheDataElseLoad = 2, //只有在没有缓存数据时从原始地址请求
NSURLRequestReturnCacheDataDontLoad = 3, //只使用缓存数据,如果不存在缓存,就会抛出异常,请求失败,用于离线模式
NSURLRequestReloadRevalidatingCacheData = 5 }; //验证本地缓存数据与远程数据是否相同,如果相同则使用本地缓存数据,否则请求远程数据.
typedef NSUInteger NSURLRequestCachePolicy;
//中文字符转换方法
-(NSString *)URLEncodedString:(NSString *)string{ //Core Foundation框架提供的C函数,可以把内容转换成为URL编码 NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, //要转换的字符串 NULL, //本身为非法URL字符但不进行编码的字符集合 CFSTR("+$,#[] "), //本身为合法的URL字符但需要进行编码的字符集合 kCFStringEncodingUTF8)); return result;}
异步GET通信方法:
异步的GET方法通过NSURLConnectionDelegate协议来调用的.协议方法如下
-(void)startAsyRequest{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp?email=%@&type=%@&action=%@", @"samrtian@xx.com", @"JSON", @"query"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if ( connection ) { _data = [NSMutableData new]; }}//失败时回调方法-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"%@", [error description]);}//接收数据时调用-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//接收完成时调用-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSDictionary *dict = [NSJSONSerialization JSONObjectWithStream:_data options:NSJSONReadingAllowFragments error:nil];}
同步POST通信方法:
//第一步,创建URL NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"]; //第二步,创建请求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET NSString *str = @"type=focus-c";//设置参数 NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data];1 //第三步,连接服务器 NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding]; NSLog(@"%@",str1);
异步POST通信方法:
-(void)startAsyPostRequest{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"xxx@mail.com", @"JSON", @"query"]; NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if ( connection ) { _data = [NSMutableData new]; }}//失败时回调方法-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"%@", [error description]);}//接收数据时调用-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [_data appendData:data];}//接收完成时调用-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSDictionary *dict = [NSJSONSerialization JSONObjectWithStream:_data options:NSJSONReadingAllowFragments error:nil];}
下边介绍一下第三方的HTTP框架
ASIHTTPRequest框架是基于OC的优秀的第三方HTTP框架,支持MAC OS 和 IOS下的开发.
下载地址: https://github.com/pokeb/asi-http-request/tree
技术支持: http://allseeing-i.com/ASIHTTPRequest
框架的优点如下:
1.支持将下载的数据放在内存或本地文件中
2.容易访问请求和应答HTTP头
3.支持cookie
4.支持gzip请求或应答
5.缓存
6.支持同步或异步请求
7.支持HTTPS
但是不支持ARC. 如果要在ARC下开发配置起来还是比较麻烦的.
第一步为工程添加支持的类库和框架
CFNetwork.framework
SystemConfiguration.framework
MobileCoreServices.framework
CoreGraphics.framework
libz.dylib
libxml2.dylib
编译的时候如果提示找不头文件那么指定头文件查找路径为${SDK_DIR}/usr/include/libxml2 就行了
第二步为修改编译参数让编译的时候对这些不支持ARC的文件跳过
如图:
到此,配置OK
下边是代码部分
同步GET请求
#import "ASIHTTPRequest.h"-(void)startSyGetRequest{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp?email=%@&type=%@&action=%@", @"samrtian@xx.com", @"JSON", @"query"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request startSynchronous]; NSError *erro = [request error]; //线程处于一直等待中完成后开始执行下边 if ( !error ) { NSData *data = [request responseData]; NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; }}
同步POST请求
#import "ASIFormDataRequest.h"-(void)startSyPostRequest{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:@"xx@mail.com" forKey:@"email"]; [request setPostValue:@"JSON" forKey:@"type"]; [request setPostValue:@"query" forKey:@"action"]; [request startSynchronous]; NSError *error = [request error]; //线程处于一直等待中完成后开始执行下边 if ( !error ) { NSData *data = [request responseData]; NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; }}
异步GET和POST请求
-(void)startSyGetRequest{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp?email=%@&type=%@&action=%@", @"samrtian@xx.com", @"JSON", @"query"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; [request startAsynchronous];}-(void)requestFinished:(ASIHTTPRequest *)request{ NSData *data = [request responseData];}-(void)requestFailed:(ASIHTTPRequest *)request{ NSError *error = [request error]; NSLog(@"%@", [error description]);}
这两个的委托方法都是一样的.POST的就不说了.还可以自定义回调方法
[request setDidFinishSelector:@selector(xxx)];
ASIHTTPRequest还支持队列并发功能.代码如下
#import "ASIHTTPRequest.h"#import "ASINetworkQueue.h"-(void)startSyGetRequest{ ASINetworkQUeue *networkQueue; networkQueue = [[ASINetworkQueue alloc] init]; //停止以前的队列 [networkQueue cancelAllOperations]; //创建ASI队列 [networkQueue setDelegate:self]; [networkQueue setRequestDidFinishSelector:@selector(requestFinished:)]; ... for (int i = 1; i < 3; i++) { NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp?email=%@&type=%@&action=%@", @"samrtian@xx.com", @"JSON", @"query"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; request.tag = i; [networkQueue addOperation:request]; } [networkQueue go];}-(void)requestFinished:(ASIHTTPRequest *)request{ NSData *data = [request responseData]; if ( request.tag == 1 ) { }else if ( request.tag == 2 ) { }}
#import "ASIFormDataRequest.h"-(void)Updata{ NSString *strURL = [[NSString alloc] initWithFormat:@"http://xxxx.com/xxx/xx.jsp"]; NSURL *url = [NSURL URLWithString:[self URLEncodedString:strURL]]; //网络传输的时候不能有中文等特殊字符,如果有得转换一下 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:@"xx@mail.com" forKey:@"email"]; [request setPostValue:@"updata" forKey:@"action"]; NSString *path = [[NSBundle mainBundle] pathForResource:@"test1" ofType:@"jpg"]; [request setFile:path forKey:@"file"]; [request setDelegate:self]; [request setDidFinishSelector:@"requestSucess:"]; [request startAsynchronous];}-(void)requestSucess:(ASIHTTPRequest *)request{ NSLog(@"上传文件成功");}
总之这章内容好多,得多加练习
- IOS 之 网络通信Web Servic
- 发布部署Web Servic
- servic
- IOS 之 网络通信数据交换格式
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- iOS网络通信http之NSURLConnection
- 使用axis开发web servic客户端
- JavaScript跨域请求RESTful Web Servic
- iOS 中客户端和服务器的 Web Service 网络通信
- iOS 开发 网络编程详解之基本网络通信过程
- ios网络通信
- ios网络通信
- java IO 总结
- USB基本问题及答案
- J2EE程序的性能优化技巧
- hadoop1.2.1 C 编程环境配置
- MySQL服务器性能剖析
- IOS 之 网络通信Web Servic
- Java中Date类和Calendar类
- 领域模型驱动应用心得....
- 在ubuntu下,切换用户
- boadcom x86_64 431*系列无线网卡驱动在linux 3.10以上内核编译问题的解决
- 李维的博客
- 逆波兰表示法Reverse Polish Notation
- 2D小游戏——泡泡球游戏
- Zookeeper总结