一、同步请求,代码如下,假设这是一个按钮点击响应的方法:
-(IBAction) requestAction: id(sender) {
NSURL *url = [NSURL urlWithString:@"http://www.hao.123.com"];
NSMutableURLRequest *request = [NSMUtableURLRequest requestWithURL:rul];
//设置同步请求方式,get方法没有请求体
[request setHTTPMethod: @"GET"];
//设置请求超时时间
[request setTimeOutInterval: 60];
NSHTTPResponse *response = nil ;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronnousRequest: request
returningResponse:&response error: &error];
//取得响应返回的编码
NSInteger statuseCode = response.statusCode;
//取得返回的响应头
NSDictionary *headFile = response.allHeadFields;
NSString *htmlString = [[NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@" , htmlString);
}
二、异步请求,使用普通方法实现代码如下:
首先得在.h文件中实现协议<NSURLConnectionDataDelegate>。并且定义一个接收数据的全局变量:NSMutabledata
*resultData; 并且在viewDidLoad方法中初始化:resultData =[ [NSMutableData alloc] init];
-(IBAction)asycchAction: id(sender) {
NSURL *url = [NSURL urlWithString:@"http://www.hao.123.com"];
NSMutableURLRequest *request = [NSMUtableURLRequest requestWithURL:rul];
[request setHTTPMethod: @"GET"];
//设置请求超时时间
[request setTimeOutInterval: 60];
//设置代理[NSURLConnection connectionWithRequest: request
delegate:self];
}
#pragma mark - NSURLConnection delegate
//请求有响应时返回此方法
-(void) connection:(NSURLConnection *)connecion didReceiveReponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResp = [NSHTTPURLResponse*] response;
NSDictionnary *allHeaderFields = [httpResp allHeadFields ];
NSLog(@"%@" allHeaderFields);
}
//接收数据的协议方法,数据的接收是一部分一部分的传送过来的,需要多次调用该方法
-(void) connection: (NSURLConnection *)connection didReceiveData:(NSData *) data{
[resultData appendData:data];
}
//数据加载完成之后调用的方法
-(void) connectionDidFinishLoading: (NSURLConnection *) connection{
NSString *htmlString = [[NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@" , htmlString);}
-(IBAction)asycchAction: id(sender) {
NSURL *url = [NSURL urlWithString:@"http://www.hao.123.com"];
NSMutableURLRequest *request = [NSMUtableURLRequest requestWithURL:rul];
[request setHTTPMethod: @"GET"];
//设置请求超时时间
[request setTimeOutInterval: 60];
NSOprationQueue *operationQueue = [[NSOprationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue: operationQueue
completionHandler: ^(NSURLResponse *response,NSData *data,NSError *error){
if([NSThread isMultiThread]){
NSLog(@"是多线程!");
}
//若是要更新UI,则需要返回到主线程中执行,如[self performSelectorOnMainThread :@selector(reloadData) withObject:nil waitUntilDone:NO];
NSString *result= [[NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
}];
}