NSURLConnection和NSMutableURLRequest 实现同步、异步请求
我是走向ios的一个小书童,我有很多不懂的,新鲜的知识去学习,去掌握!
一、同步请求-GET方式
// 要请求的地址
NSString *urlString=@"地址,我就只有保密了!你懂的";
// 将地址编码
urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
// 实例化NSMutableURLRequest,并进行参数配置
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString: urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval: 60];
[request setHTTPShouldHandleCookies:FALSE];
[request setHTTPMethod:@"GET"];
// Response对象,用来得到返回后的数据,比如,用statusCode==200 来判断返回正常
NSHTTPURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
// 处理返回的数据
NSString *strReturn = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",strReturn);
NSLog(@"%d",[response statusCode]);
// 对象还是要释放的
[request release];
[strReturn release];
@interface MoreViewController : UIViewController<</span>NSURLConnectionDelegate>
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:request delegate: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 isEqual: aSynConnection])
{
NSString *asyReturn = [[NSString alloc] initWithData:returnInfoData encoding:NSUTF8StringEncoding];
NSLog(@"%@",asyReturn);
[returnInfoData release];
returnInfoData = nil;
[asyReturn release];
}
}
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
@protocol NSURLConnectionDelegate <<span style="color: #743fa4">NSObject>
@protocol NSURLConnectionDataDelegate <<span style="color: #743fa4">NSURLConnectionDelegate>