iPhone应用用HTTP协议

iPhone应用HTTP协议服务器通信是本文要介绍的内容,主要是来学习iphone应用中的通信协议,具体内容来看本文详解。

iPhone用http协议和服务器通信有两种方 式,一种是同步一种是异步的,所谓同步是指当客户端调用post/get的方式的函数向服务器发出数据请求后,该函数不会直接返回,只有得到服务器响应或 者请求时间timeout之后才会返回继续执行其它任务。异步采用回调的方式,即请求发送后,函数会立即返回,一旦服务器联结成功操作系统会去触发相应的 回调进行相应的处理。这和window的消息处理机制一样。

同步一般用于一次性操作,如判断当前网络是否可用等等。多的就不再一一介绍,在实现上面有两点不同:

(1)在用NSURLConnect的时候一个调用同步函数一个调用了异步函数。

(2)异步的需要实现delegate的相关回调函数。

以下是参考代码:

同步方式:

 
 
  1. -(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{  
  2. NSLog(urlstr);  
  3. NSLog(strcontext);  
  4. assert(strcontext != NULL);  
  5. assert(urlstr != NULL);  
  6. NSData*postData=[strcontextdataUsingEncoding:NSASCIIStringEncoding  allowLossyConversion:YES];   
  7. NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];   
  8. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];   
  9. [request setURL:[NSURL URLWithString:urlstr]];   
  10. [request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout  
  11. [request setValue:postLength forHTTPHeaderField:@"Content-Length"];   
  12. [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];   
  13. [request setHTTPBody:postData];   
  14. NSURLResponse *respone;  
  15. NSError *error;  
  16. NSData*myReturn=[NSURLConnection  sendSynchronousRequest:request returningResponse:&respone  
  17. error:error];  
  18. NSLog(@"%@", [[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding]);  

异步方式:

 
 
  1. -(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{  
  2. NSLog(urlstr);  
  3. NSLog(strcontext);  
  4. assert(strcontext != NULL);  
  5. assert(urlstr != NULL);  
  6. NSData *postData = [strcontext dataUsingEncoding:NSASCIIStringEncoding  allowLossyConversion:YES];   
  7. NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];   
  8. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];   
  9. [request setURL:[NSURL URLWithString:urlstr]];   
  10. [request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout  
  11. [request setValue:postLength forHTTPHeaderField:@"Content-Length"];   
  12. [request setValue:@"application/x-www-form-urlencoded"  forHTTPHeaderField:@"Content-Type"];   
  13. [request setHTTPBody:postData];   
  14. NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request  delegate:self];   
  15. if (conn)     
  16. {   
  17. NSLog(@"Connection success");  
  18. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  
  19. [conn retain];  
  20. }     
  21. else     
  22. {   
  23. // inform the user that the download could not be made   
  24. }   
  25. }  
  26. #pargma mark 

以下为相应的回调函数

 
 
  1. // 收到响应时, 会触发  
  2. - (void)connection:(NSURLConnection *)connection   didReceiveResponse:(NSURLResponse *)response  {  
  3. // 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去  
  4. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;  
  5. if ([response respondsToSelector:@selector(allHeaderFields)]) {  
  6. NSDictionary *dictionary = [httpResponse allHeaderFields];  
  7. NSLog([dictionary description]);  
  8. NSLog(@"%d",[response statusCode]);  
  9. }  
  10. }  
  11. //链接错误    
  12. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {  
  13. //[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil  waitUntilDone:NO];  
  14. NSLog(@"%@",[error localizedDescription]);  
  15. }  
  16. // Called when a chunk of data has been downloaded.  
  17. //接收数据 每收到一次数据, 会调用一次  
  18. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  
  19. // Process the downloaded chunk of data.  
  20. NSLog(@"%d", [data length]);  
  21. //NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);  
  22. //[self performSelectorOnMainThread:@selector(updateProgress) withObject:nil  waitUntilDone:NO];  
  23. }  
  24. //接收结束  
  25. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {  
  26. NSLog(@"%@",connection);  
  27. //NSLog(@"%lld", received_);  
  28. //[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil  waitUntilDone:NO];  
  29. // Set the condition which ends the run loop.  
  30. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值