关于iOS中的短连接方法

1.同步方式请求——Get方式

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.bafdaidu.com"]];

 req.timeoutInterval = 15;

[req setHTTPMethod:@"GET"];

// Response对象,用来得到返回后的数据,比如,用statusCode==200 来判断返回正常

NSHTTPURLResponse *response;

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

// 处理返回的数据

NSString *strReturn = [[NSString alloc] initWithData:returnDataencoding:NSUTF8StringEncoding];

NSLog(@"%@",strReturn);

NSLog(@"%d",[response statusCode]);

// 对象还是要释放的

[strReturn release];

2.异步方式请求

1.在*.h文件中,实现NSURLConnectionDelegate协议。
例如:

@interface MoreViewController : UIViewController<</span>NSURLConnectionDelegate>


2.在*.m文件中,进行异步请求和实现协议方法。
异步请求:
NSString   *urlString= @"地址,我就只有保密了!你懂的" ;

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString: urlString]];

[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

[request setTimeoutInterval: 60];

[request setHTTPShouldHandleCookies:FALSE];

[request setHTTPMethod:@"GET"];

    // NSURLConnection* aSynConnection 可以申明为全局变量.

    // 在协议方法中,通过判断aSynConnection,来区分,是哪一个异步请求的返回数据。

    aSynConnection = [[NSURLConnection alloc] initWithRequest:requestdelegate:self];

协议方法:

 

#pragma mark- NSURLConnectionDelegate 协议方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{

    NSLog(@"请求成功!");

    returnInfoData=[[NSMutableData alloc]init];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [returnInfoData appendData:data];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error{

    NSLog(@"didFailWithError");

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    if( [connection isEqualaSynConnection])

    {

        NSString *asyReturn = [[NSString alloc] initWithData:returnInfoDataencoding:NSUTF8StringEncoding];

        NSLog(@"%@",asyReturn);

        [returnInfoData release];

        returnInfoData = nil;

        [asyReturn release];

    }

}

3.POST方式:

注意这个类要

UIResponder <UIApplicationDelegate, NSURLConnectionDelegate>

在请求的地方加上一下的代码:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.bafdaidu.com"]];

    

    req.timeoutInterval = 15;

    [req setHTTPMethod:@"POST"];

    NSData *postdata;

    postdata = [@"{}" dataUsingEncoding:NSASCIIStringEncoding];


    if(postdata!=nil){


        [req setHTTPBody:postdata];

        [req setValue:[NSString stringWithFormat:@"%d", [postdata length]] forHTTPHeaderField:@"Content-Length"];

        [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    }

    

    [[NSURLConnection connectionWithRequest:req delegate:self] start];


///下面是回调的地方

#pragma mark NSURLConnectionDelegate


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    int statusCode = [((NSHTTPURLResponse*)response) statusCode];

    

    NSLog(@"%@: %@ : statusCode=%d", NSStringFromSelector(_cmd), self, statusCode );

    

    if( statusCode >= 400 )

    {

        

    }

    data = [[NSMutableData alloc] init];

    

    long long totalBytes = [response expectedContentLength];

    NSLog(@"总共的字数为:%lld",totalBytes);

}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receiveData

{

    [data appendData:receiveData];

}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSString * strValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@", strValue);

    NSLog(@"recieve finish");

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"%@: %@", NSStringFromSelector(_cmd), self );

    [connection cancel];

    int                     errorCode       = [error code];

    NSString                *errorMessage   = [NSString stringWithFormat:@"ErrorCode : %d", errorCode];

}

//end





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值