Iphone开发-NSRULRequest,及NSTRLConnection概述:
HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
HUD.labelText = @"Load Web Server";
//HUD.delegate = self;
NSURL *url = [NSURL URLWithString:@"http://www.facebook.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url];
[request setTimeoutInterval:5];
NSLog(@"request1::%d",[request timeoutInterval]);
//NSHTTPURLResponse *response;
NSURLConnection *connnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
CFRunLoopRun();
//[connnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSLog(@"request2::%d",[request timeoutInterval]);
[connnection release];
// 异步访问时则要实现委托的一个方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(@"%@",[dictionary description]);
NSLog(@"%d",[httpResponse statusCode]);
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
finished = TRUE;
if (HUD) {
[HUD removeFromSuperview];
}
[self.view setNeedsDisplay];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
if (HUD) {
[HUD removeFromSuperview];
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ERROR" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
NSConnection概述:
}
1、NSURLConnection类的作用是异步下载url请求的内容。因此,在使用此类时,没必要在开一个线程来处理。
2、当其检测到所指向的url要重定向到一个新地址时,它的delegate会接到消息“connection:willSendRequest:redirectResponse: ”,
在这个消息处理函数中,你可以允许重定向或指定其它url,也可以拒绝重定向。
3、它有一个简易的类方法“sendSynchronousRequest:returningResponse:error:”,可以用来同步载入url请求的内容。
异步请求
NSMutableData* buf = [[NSMutableData alloc] initWithLength:0];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
// 收到响应时, 会触发
- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse;
// 你可以在里面判断返回结果, 或者处理返回的http头中的信息
// 每收到一次数据, 会调用一次
- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data;
// 因此一般来说,是
- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data
{
[buf appendData:data];
}
// 当然buffer就是前面initWithRequest时同时声明的.
// 网络错误时触发
- (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error;
// 全部数据接收完毕时触发
- (void)connectionDidFinishLoading:(NSURLConnection *)aConn;
同步請求
// 初始化請求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // 設置URL
[request setURL:[NSURL URLWithString:urlStr]];
// 設置HTTP方法
[request setHTTPMethod:@"GET"];
// 發送同步請求, 這裡得returnData就是返回得數據楽
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
// 釋放對象
[request release];