#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//同步请求
//[NSURLConnection sendSynchronousRequest:<#(NSURLRequest *)#> returningResponse:(NSURLResponse *__autoreleasing *) error:<#(NSError *__autoreleasing *)#>];
/*
NSURL对象初始化注意:
1.url里面有空格。
2.url里面不能有汉字。
*/
NSString *urlString = @"http://d3.s.hjfile.cn/2012/201202_3/43904b09-24e1-4fdb-8b46-d3dba3323278.mp3";
//有中文需要utf8编码
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//1.url
NSURL *url = [NSURL URLWithString:urlString];
//如果url里面有汉字,需要编码
//取以/分割,分割的字符串的最后一部分
//[url lastPathComponent];
NSLog(@"--- %@",url);
//2.请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
#pragma mark - 异步请求的第1种方式:
/*
sendAsynchronousRequest:请求对象
queue:队列
completionHandler:请求完成的回调
*/
//3.发送异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"请求到的数据----%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//[NSURLConnection connectionWithRequest:<#(NSURLRequest *)#> delegate:<#(id)#>];
#pragma mark - 异步请求的第2种方式:
//1.创建NSURLConnection对象
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
//2.手动启动请求
[connection start];
#pragma mark - 异步请求的第3种方式:
//发送异步请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark - NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//1.文件名字
NSString *fileName = [response suggestedFilename];
NSLog(@"filename=%@",fileName);
//2.文件大小,单位字节
long long fileSize = [response expectedContentLength];
//3.文件类型
NSString *type = [response MIMEType];
NSLog(@"type=%@",type);
//4.状态码
//404,403 ,500,200
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger code = httpResponse.statusCode;
NSLog(@"状态码:%ld",code);
//5.响应头信息
NSDictionary *headerFields = [httpResponse allHeaderFields];
NSLog(@"响应头:%@",headerFields);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//1.追加数据
//2.计算进度
//3.刷新界面
//4.写入数据
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//1.刷新界面
//2.数据解析和封装数据模型
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网络请求的封装
最新推荐文章于 2025-08-15 09:36:38 发布