iphone客户端与Web服务端交互

iphone客户端和服务端交互一般来说,只需简单的两步骤:

第一步:定义一个请求

NSMutableURLRequest*urlRequest =[[NSMutableURLRequest alloc]initWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:NETWORK_TIMEOUT];
url参数就是一个http地址
NSMutableURLRequest有诸如setHTTPMethod、setValue、setHTTPBody之类的方法

 第二步:发送一个请求

NSURLConnection* connection= [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
 
[connection start];

connection的delegate负责服务器端返回数据的接收,这个delegate(NSURLConnectionDataDelegate)实现如下一些方法:

-(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse*)response;

  接收并响应会调用此方法

-(void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error;

 网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法

-(void)connection:(NSURLConnection *)connectiondidReceiveData:(NSData*)data;

 

接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次

 

猜你喜欢

转载自1395014506.iteye.com/blog/2260080