iOS开发网络层

http和https数据请求

  • http和https请求的基本概念

HTTP+加密+认证+完整性保护=HTTPS

  • iOS原生http/https网络实现方案

    • 实现尝试
    • 原理初探

第三方库 AFNetworking网络层实现方案

简单网络请求

AFHTTPSessionManager

  • 属性
@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;

/**
 Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.

 @warning `requestSerializer` must not be `nil`.
 */
@property (nonatomic, strong) AFHTTPRequestSerializer  * requestSerializer;

/**
 Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.

 @warning `responseSerializer` must not be `nil`.
 */
@property (nonatomic, strong) AFHTTPResponseSerializer  * responseSerializer;

///-------------------------------
/// @name Managing Security Policy
///-------------------------------

/**
 The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception.
 */
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;

注: 原生请求的入参和出参都是NSData格式的,所以通过requestSerializer将入参进行序列化,通过 responseSerializer对出参进行序列化

  • 初始化
+ (instancetype)manager {
    return [[[self class] alloc] initWithBaseURL:nil];
}

- (instancetype)init {
    return [self initWithBaseURL:nil];
}

- (instancetype)initWithBaseURL:(NSURL *)url {
    return [self initWithBaseURL:url sessionConfiguration:nil];
}

注: 以前一直以为[AFHTTPSessionManager manager]是单例,但从源码来看并不是单例。

  • get/post请求


    示意图
/**
请求
 @param URLString 请求链接
 @param parameters 请求入参
 @param success 请求成功出参
 @param failure 请求失败出参

 @see -dataTaskWithRequest:completionHandler:
 */
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
                   parameters:(nullable id)parameters
                      success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure ;

- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(nullable id)parameters
                       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure 

**
 http请求

 @param method 请求方法: Get/Post
 @param URLString 请求链接
 @param parameters 请求入参
 @param uploadProgress 上传进度
 @param downloadProgress 下载进度
 @param success 请求成功回掉block
 @param failure 请求失败block
 @return 本次请求task
 */
- (NSURLSessionDataTask *) dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
    if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }

        return nil;
    }

    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [self dataTaskWithRequest:request
                          uploadProgress:uploadProgress
                        downloadProgress:downloadProgress
                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
        if (error) {
            if (failure) {
                failure(dataTask, error);
            }
        } else {
            if (success) {
                success(dataTask, responseObject);
            }
        }
    }];

    return dataTask;
}

AFHTTPRequestSerializer

请求解析类族
  • 属性
/**
字符编码
 */
@property (nonatomic, assign) NSStringEncoding stringEncoding;

/**
是否使用移动网络(蜂窝网络)
 */
@property (nonatomic, assign) BOOL allowsCellularAccess;

/**
缓存策略
 */
@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;

/**
请求中是否包含cookies
 */
@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;

/**
是否进行三次握手
 */
@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;

/**
网络服务类型:
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
};
 */
@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;

/**
超时时间
 */
@property (nonatomic, assign) NSTimeInterval timeoutInterval;

/**
默认http请求头内容
 */
@property (readonly, nonatomic, strong) NSDictionary  *HTTPRequestHeaders;
  • 常用方法
    • 初始化

Socket

  • Socket的基本概念

  • iOS原生Socket连接实现方案

  • 第三方库CocoaAsyncSocket网络层实现方案

你可能感兴趣的:(iOS开发网络层)