iphone判断是否联网(http),接受和发送数据
2012-05-30 17:14
323 查看
iphone判断是否联网(http),接受和发送数据 1.判断是否联网: -(BOOL) isConnected { //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; // Recover reachability flags SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); SCNetworkReachabilityFlags flags; //获得连接的标志 BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); CFRelease(defaultRouteReachability); //如果不能获取连接标志,则不能连接网络,直接返回 if (!didRetrieveFlags) { return NO; } //根据获得的连接标志进行判断 BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; return (isReachable && !needsConnection) ? YES : NO; } 2.发送数据 -(NSData *)sendPostRequest:(NSString *)postString theUrl:(NSString *)urlString{ //NSError *error=[[NSError alloc] autorelease]; NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSURL *url=[[NSURL alloc]initWithString:urlString]; NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init]; [request setURL: url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"]; // [request setTimeoutInterval:15]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPBody:postData]; //定义一个计时器 connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true]; [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(cancelConnection:) userInfo:nil repeats:NO]; [url release]; [request release]; if(connection) { receivedData = [[NSMutableData data] retain]; } else { NSLog(@"<<Net_Http.m-->sendPostRequest-->connection-->nil"); } //暂停,等待NSTimer的结束 while(!finished) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } return receivedData; } 3.接受数据 -(NSData *)sendGetRequest:(NSString *)getString theUrl:(NSString *)urlString{ //NSError *error=[[NSError alloc] autorelease]; NSData *getData = [getString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *getLength = [NSString stringWithFormat:@"%d", [getData length]]; NSURL *url=[[NSURL alloc]initWithString:urlString]; NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init]; [request setURL: url]; [request setHTTPMethod:@"GET"]; [request setValue:getLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"]; // [request setTimeoutInterval:15]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPBody:getData]; //定义一个计时器 connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true]; [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(cancelConnection:) userInfo:nil repeats:NO]; [url release]; [request release]; if(connection) { receivedData = [[NSMutableData data] retain]; } else { NSLog(@"<<Net_Http.m-->sendGetRequest-->connection-->nil"); } while(!finished) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } return receivedData; } 4.json连接网络的代理函数 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"<<Net_Http.m-->connection-->didReceiveResponse-->get the whole response:%@",response); [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"<<Net_Http.m-->connection-->didReceiveData-->getting data"); [receivedData appendData:data]; } -(void)connection:(NSURLConnection *)connection_ didFailWithError:(NSError *)error { if (mianViewLoadFlag==YES) { NSLog(@"<<Net_Http.m-->connection-->didFailWithError-->加载完成!"); receivedData=nil; [self connectionDidFinishLoading:connection_]; }else { NSLog(@"<<Net_Http.m-->connection-->didFailWithError-->加载出错!"); [self showErrorAlert:@"网络错误\n请检查您的网络或稍后重试"]; [self connectionDidFinishLoading:connection_]; } } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { finished=YES; mianViewLoadFlag=YES; NSLog(@"<<Net_Http.m-->connectionDidFinishLoading-->YES"); } 4. -(void)cancelConnection:(NSTimer *)timer{ //取消连接 NSLog(@"<<Net_Http.m-->cancelConnection-->计时器已到时间"); [self connection:connection didFailWithError:error]; [connection cancel]; } -(void)showErrorAlert:(NSString *)message{ myAlert = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil]; [myAlert show]; [myAlert release]; } -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ // if (alertView == myAlert) { switch (buttonIndex) { case 0: //[[UIApplication sharedApplication] terminateWithSuccess]; break; case 1: break; default: break; } // } } -(void)setMainViewLoadFlag:(BOOL)mainFlag{ mianViewLoadFlag=mainFlag; } 5.NET_HTTP.h BOOL mianViewLoadFlag; @interface Net_Http : NSObject { NSURLConnection *connection; NSMutableData *receivedData; BOOL finished; UIAlertView *myAlert; NSError *error; } -(NSData *)sendPostRequest:(NSString *)postString theUrl:(NSString *)urlString; -(NSData *)sendGetRequest:(NSString *)getString theUrl:(NSString *)urlString; -(void)showErrorAlert:(NSString *)message; -(BOOL) isConnected; -(BOOL)setMainViewLoadFlag;原文地址:http://www.cnblogs.com/pengyingh/articles/2346124.html
相关文章推荐
- 【整理】Asp.net HttpWebRequest和HttpWebResponse发送和接受任何类型数据
- jQuery发送ajax请求并把得到的数据存放到数组中并判断是否有某值
- Asp.net HttpWebRequest和HttpWebResponse发送和接受任何类型数据
- iPhone HTTP Post发送数据心得
- 怎么通过http向服务器发送数据并接受到返回的数据
- Asp.net HttpWebRequest和HttpWebResponse发送和接受任何类型数据
- java模拟http发送请求与接受返回数据
- 【整理】Asp.net HttpWebRequest和HttpWebResponse发送和接受任何类型数据
- 判断iPhone是否联网状态
- http服务向服务器发送并接受数据--------------HttpClient对象向服务器发送并接受数据
- Asp.net HttpWebRequest和HttpWebResponse发送和接受任何类型数据
- C# 中TCP连接通过数据接收来判断连接是否断开
- C#_判断本机是否联网
- HttpClient判断网络是否连接
- AJAX,使用XMLHttpRequest接受客户端的提交,并发送响应
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- PHP - Manual手册 - XL. Filesystem 文件系统函数 - is_uploaded_file判断文件是否是通过 HTTP POST 上传的
- phpl判断mysq数据库中的某个数据表是否存在的方法总结
- web项目如何知道给别人发送的邮箱,判断用户是否读了邮件
- java socket 连接数据传输判断是否结束