iOS里面用NSURLRequestNSURLMutableRequest来表示一个请求,可以进行一些基本的设置。

有几种初始化的方法:

+ (instancetype)requestWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;参数分别是URL,缓存策略,超时时间

- (instancetype)initWithURL:(NSURL *)URL;参数是URL

- (instancetype)initWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;参数是URL,缓存策略,超时时间

有一些属性:

@property (nullable, copy) NSURL *URL;

@property NSURLRequestCachePolicy cachePolicy;

@property NSTimeInterval timeoutInterval;

@property (nullable, copy) NSURL *mainDocumentURL;主要是用于在同一个domain下面加载cookie时的策略,这个属性暂时没有在framework里面被使用。

@property NSURLRequestNetworkServiceType networkServiceType 这个属性是和request有关的,表示网络服务类型。这个提示有助于系统优化通信,确定唤醒蜂窝数据或者WIFI的速度。调节不同的参数,可以平衡电池、性能以及其他因素。

NSURLRequestNetworkServiceType有以下几种类型

typedef NS_ENUM(NSUInteger, NSURLRequestNetworkServiceType)
{
    NSURLNetworkServiceTypeDefault = 0,	// Standard internet traffic
    NSURLNetworkServiceTypeVoIP = 1,	// Voice over IP control traffic
    NSURLNetworkServiceTypeVideo = 2,	// Video traffic
    NSURLNetworkServiceTypeBackground = 3, // Background traffic
    NSURLNetworkServiceTypeVoice = 4,	   // Voice data
    NSURLNetworkServiceTypeCallSignaling API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0)) = 11, // Call Signaling
};
  • NSURLNetworkServiceTypeDefault是创建request的时候默认的

  • NSURLNetworkServiceTypeVoIP表明这个request是请求VoIP的

  • NSURLNetworkServiceTypeVideo表明这个request是请求vedio的

  • NSURLNetworkServiceTypeBackground表明这个请求是在后台的

  • NSURLNetworkServiceTypeVoice表明这个请求是音频请求

  • NSURLNetworkServiceTypeCallSignaling表示(电台、电视台等)的呼叫信号

@property BOOL allowsCellularAccess该属性默认是YES。该属性表示是否允许使用移动数据来请求。这个标识会把WiFi和电量都考虑在内。

@property NSURLRequestCachePolicy cachePolicy;缓存策略

只有http和https才有缓存策略

看一下几种缓存策略,即NSURLRequestCachePolicy的几种类型:

typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy)
{
    NSURLRequestUseProtocolCachePolicy = 0,

    NSURLRequestReloadIgnoringLocalCacheData = 1,
    NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented
    NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,

    NSURLRequestReturnCacheDataElseLoad = 2,
    NSURLRequestReturnCacheDataDontLoad = 3,

    NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
};
  • NSURLRequestUseProtocolCachePolicy,默认的缓存策略, 如果缓存不存在,直接从服务端获取。如果缓存存在,会根据response中的Cache-Control字段判断下一步操作,如: Cache-Control字段为must-revalidata, 则询问服务端该数据是否有更新,无更新的话直接返回给用户缓存数据,若已更新,则请求服务端。在这个缓存策略下,NSURLReqeust、NSURLMutableRequest默认的超时时间是60s.

  • NSURLRequestReloadIgnoringLocalCacheData, 忽略本地缓存数据,直接请求服务端.

  • NSURLRequestIgnoringLocalAndRemoteCacheData,忽略本地缓存,代理服务器以及其他中介,直接请求源服务端

  • NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData

  • NSURLRequestReturnCacheDataElseLoad,有缓存就使用,不管其有效性(即忽略Cache-Control字段), 无则请求服务端.

  • NSURLRequestReturnCacheDataDontLoad, 死活加载本地缓存. 没有就失败. (确定当前无网络时使用)

  • NSURLRequestReloadRevalidatingCacheData,缓存数据必须得得到服务端确认有效才使用(貌似是NSURLRequestUseProtocolCachePolicy中的一种情况)


GET请求

先自己拼一个请求构造一个URL,在生成URL之前先要urlEncode一下stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding(关于stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding并不能对所有特殊字符进行编码的解决办法, 在别的日志里的有提到)。

再设置NSMutableURLRequest的HTTPMethod@"GET"

一般我的构造方法如下:

   NSDictionary * paramDic = @{@"key1":@"v1",
                                @"key2":@"v2",
                                @"key3":@"v3"};
    
    NSMutableString * string = [NSMutableString stringWithString:@"http://www.yourhost.com"];
    NSArray * keys = [paramDic allKeys];
    for (int i = 0; i < [keys count]; i ++) {
        if (0 == i) {
            [string appendString:@"?"];
            [string appendString:keys[i]];
            [string appendString:@"="];
            [string appendString:[paramDic objectForKey:keys[i]]];
        } else {
            [string appendString:@"&"];
            [string appendString:keys[i]];
            [string appendString:@"="];
            [string appendString:[paramDic objectForKey:keys[i]]];
        }
    }
    NSURL * url = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"]; // 设置请求方式
    [request setTimeoutInterval:10.0]; // 设置超时时间


构造POST请求的时候,需要把key-value放在body里面

    NSDictionary * paramDic = @{@"key1":@"v1",
                                @"key2":@"v2",
                                @"key3":@"v3"};
    
    NSMutableString * string = [NSMutableString string];
    NSArray * keys = [paramDic allKeys];
    for (int i = 0; i < [keys count]; i ++) {
        if (0 == i) {
            [string appendString:keys[i]];
            [string appendString:@"="];
            [string appendString:[paramDic objectForKey:keys[i]]];
        } else {
            [string appendString:@"&"];
            [string appendString:keys[i]];
            [string appendString:@"="];
            [string appendString:[paramDic objectForKey:keys[i]]];
        }
    }
    NSURL * url1 = [NSURL URLWithString:@"http://www.yourhost.com"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"]; // 设置请求方式
    [request setTimeoutInterval:10.0]; // 设置超时时间
    [request setHTTPBody:[[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]]; // 设置HTTP BODY