-(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;