网络 NSURLConnection

2017-02-21  本文已影响0人  Helen_kay

NSURLConnection的使用步骤

D45DA60B-7CE2-4642-A159-59E8B1BCD4C5.png

NSURLConnection常见的发送请求方法有以下几种
同步请求

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;

异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
block回调

+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;

代理

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;

在startImmediately = NO的情况下,需要调用start方法开始发送请求

成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议

NSURLConnectionDataDelegate协议中的代理方法

开始接收到服务器的响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

服务器返回的数据完全接收完毕后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

请求出错时调用(比如请求超时)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

NSMutableURLRequest

NSMutableURLRequest是NSURLRequest的子类,常用方法有

创建GET和POST请求

创建GET请求

NSString *urlStr = [@"http://192.168.1.102:8080/MJServer/login?username=123&pwd=123" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

创建POST请求

NSString *urlStr = @"http://192.168.1.102:8080/MJServer/login";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 请求体
NSString *bodyStr = @"username=123&pwd=123";
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

发送JSON给服务器

如何发送JSON给服务器:

数据安全

用户的隐私数据
登录密码
银行账号
… …

仅仅用POST请求提交用户的隐私数据,还是不能完全解决安全问题
可以利用软件(比如Charles)设置代理服务器,拦截查看手机的请求数据
因此:提交用户的隐私数据时,一定不要明文提交,要加密处理后再提交

常见的加密算法
MD5 \ SHA \ DES \ 3DES \ RC2和RC4 \ RSA \ IDEA \ DSA \ AES

加密算法的选择
一般公司都会有一套自己的加密方案,按照公司接口文档的规定去加密

  • 什么是MD5
    全称是Message Digest Algorithm 5,译为“消息摘要算法第5版”
    效果:对输入信息生成唯一的128位散列值(32个字符)
  • MD5的特点
    输入两个不同的明文不会得到相同的输出值
    根据输出值,不能得到原始的明文,即其过程不可逆
  • MD5的应用
    由于MD5加密算法具有较好的安全性,而且免费,因此该加密算法被广泛使用
    主要运用在数字签名、文件完整性验证以及口令加密等方面

MD5解密网站

同一个URL的多次请求

有时候,对同一个URL请求多次,返回的数据可能都是一样的
比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的


请求多次.png

上面的情况会造成以下问题

  1. 用户流量的浪费
  2. 程序响应速度不够快

为了提高程序的响应速度,可以考虑使用缓存(内存缓存\硬盘缓存)


第一次请求数据.png 服务器返回数据时.png

缓存的实现

一般只对GET请求进行缓存,不必对POST请求进行缓存
GET请求一般用来查询数据
POST请求一般是发大量数据给服务器处理(变动性比较大)

在iOS中,可以使用NSURLCache类缓存数据
iOS 5之前:只支持 内存缓存
iOS 5开始:同时支持 内存缓存 和 硬盘缓存

NSURLCache了解
缓存原理:一个NSURLRequest对应一个NSCachedURLResponse
缓存技术:数据库

NSURLCache的常见用法

获得全局缓存对象(没必要手动创建)
NSURLCache *cache = [NSURLCache sharedURLCache];

设置内存缓存的最大容量(字节为单位,默认为512KB)
- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;

设置硬盘缓存的最大容量(字节为单位,默认为10M)
- (void)setDiskCapacity:(NSUInteger)diskCapacity;

硬盘缓存的位置:沙盒/Library/Caches

取得某个请求的缓存
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;

清除某个请求的缓存
- (void)removeCachedResponseForRequest:(NSURLRequest *)request;

清除所有的缓存
- (void)removeAllCachedResponses;

缓存GET请求

要想对某个GET请求进行数据缓存,非常简单

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置缓存策略
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

只要设置了缓存策略,系统会自动利用NSURLCache进行数据缓存

缓存策略

iOS对NSURLRequest提供了7种缓存策略:(实际上能用的只有3种)
NSURLRequestUseProtocolCachePolicy // 默认的缓存策略(取决于协议)
NSURLRequestReloadIgnoringLocalCacheData // 忽略缓存,重新请求
NSURLRequestReloadIgnoringLocalAndRemoteCacheData // 未实现
NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData // 忽略缓存,重新请求
NSURLRequestReturnCacheDataElseLoad
// 有缓存就用缓存,没有缓存就重新请求

NSURLRequestReturnCacheDataDontLoad
// 有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)

NSURLRequestReloadRevalidatingCacheData // 未实现

缓存的使用注意

如果请求某个URL的返回数据

检测网络状态

在网络应用中,需要对用户设备的网络状态进行实时监控,目的是
让用户了解自己的网络状态,防止一些误会(比如怪应用无能)
根据用户的网络状态进行智能处理,节省用户流量,提高用户体验

  • WIFI\3G网络:自动下载高清图片

苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

Reachability的使用步骤

  1. 添加框架SystemConfiguration.framework
  1. 添加源代码


    添加源码.png
  2. 包含头文件
    #import "Reachability.h"

常见用法

// 是否WIFI
+ (BOOL) IsEnableWIFI {
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

// 是否3G
+ (BOOL) IsEnable3G {
    return ([[Reachability reachabilityForInternetConnectionen] currentReachabilityStatus] != NotReachable);
}

网络监控

[[NSNotificationCenter defaultCenter] addObserver:self
 selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
self.netReachability = [Reachability reachabilityForInternetConnection];
[self.netReachability startNotifier];

- (void)dealloc
{
    [self.netReachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

上一篇 下一篇

猜你喜欢

热点阅读