您的位置:首页 > 理论基础 > 计算机网络

网络:GET 的使用

2016-04-12 16:57 555 查看
#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSString *etag;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// NSURL
NSURL *url = [NSURL URLWithString:@"http://localhost/itcast/images/head1.png"];
// NSURLRequest 请求
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];

// 面试的时候问缓存怎么做?系统就可以
// 要做到,如果服务器资源发生改变,我就下载。如果没有发生改变,就使用本地缓存
// Etag = "\"b2d4-4ddbf42ea8380\""; 蓝色头像
// Etag = "\"b690-4ddbf42ea8380\""; 粉红色头像
// 如果服务器资源跟本地资源不匹配,就会返回新的数据
// 如果服务器资源跟本地资源是一样的,返回 304,判断状态码自己去取本地缓存
// 告诉服务器当前的Etag值
// 先判断Etag 是否有值
if (self.etag) {
[request setValue:self.etag forHTTPHeaderField:@"If-None-Match"];
}
// 发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
// 强转型
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"%@ -- %zd",response,data.length);
// 如果服务器返回状态码是304 证明服务器文件没有发生改变
if (httpResponse.statusCode == 304) {
// 取出缓存数据
NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache]cachedResponseForRequest:request];
data = cacheResponse.data;
NSLog(@"本地缓存");
}

// 接到二进制数据
// 转化成UIImage
UIImage *image = [UIImage imageWithData:data];
// 显示出来
self.imageView.image = image;

// 保存当前请求的Etag 值
self.etag = httpResponse.allHeaderFields[@"Etag"];
NSLog(@"etag == %@",self.etag);
}];

}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: