网络: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
相关文章推荐
- Android Volley完全解析(二),使用Volley加载网络图片
- 001-Zabbix-网络设备监控(cisco)
- 使用 AsyncTask 异步请求网络数据
- 向指定URL发送GET或POST请求(调第三方接口)
- 使用Gephi绘制动态网络的三种方法
- NFS(network file system)网络文件系统1
- Android Volley网络访问
- TCP/IP(四)ICMP协议,ping和Traceroute
- tcpdump 抓包让wireshark来分析
- Bzoj4514:[Sdoi2016]数字配对:网络流,费用流
- TCP/IP(三)IP协议,ARP协议,RARP协议
- TCP/IP(二)数据链路层
- HttpServletResponse对象应用浅析
- 查看服务器当前网络使用情况实用工具nload
- 迭代服务器与并发服务器
- 大端法、小端法、网络字节序 转
- http状态码
- 使用http协议获取网络图片
- haproxy启动故障之-"Proxy 'http_gsres': in multi-process mode."
- 虚拟机oracle virtualbox 上安装centos6.5 网络设置