主要功能介绍:

  1.GET请求操作

  2.POST请求操作

1.处理params参数(例如拼接成:usename="123"&password="123")

#import <Foundation/Foundation.h>

@interface LYURLRequestSerialization : NSObject

+(NSString *)LYQueryStringFromParameters:(NSDictionary *)parameters;

@end
#import "LYURLRequestSerialization.h"

@interface LYURLRequestSerialization()

@property (readwrite, nonatomic, strong) id  value;
@property (readwrite, nonatomic, strong) id field; @end @implementation LYURLRequestSerialization - (id)initWithField:(id)field value:(id)value {
self = [super init];
if (!self) {
return nil;
} self.field = field;
self.value = value; return self;
} #pragma mark - FOUNDATION_EXPORT NSArray * LYQueryStringPairsFromDictionary(NSDictionary *dictionary);
FOUNDATION_EXPORT NSArray * LYQueryStringPairsFromKeyAndValue(NSString *key, id value); +(NSString *)LYQueryStringFromParameters:(NSDictionary *)parameters {
NSMutableArray *mutablePairs = [NSMutableArray array];
for (LYURLRequestSerialization *pair in LYQueryStringPairsFromDictionary(parameters)) { [mutablePairs addObject:[pair URLEncodedStringValue]];
} return [mutablePairs componentsJoinedByString:@"&"];
} NSArray * LYQueryStringPairsFromDictionary(NSDictionary *dictionary) {
return LYQueryStringPairsFromKeyAndValue(nil, dictionary);
} NSArray * LYQueryStringPairsFromKeyAndValue(NSString *key, id value) {
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = value;
for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
id nestedValue = dictionary[nestedKey];
if (nestedValue) {
[mutableQueryStringComponents addObjectsFromArray:LYQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
}
}
} else if ([value isKindOfClass:[NSArray class]]) {
NSArray *array = value;
for (id nestedValue in array) {
[mutableQueryStringComponents addObjectsFromArray:LYQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
}
} else if ([value isKindOfClass:[NSSet class]]) {
NSSet *set = value;
for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
[mutableQueryStringComponents addObjectsFromArray:LYQueryStringPairsFromKeyAndValue(key, obj)];
}
} else {
[mutableQueryStringComponents addObject:[[LYURLRequestSerialization alloc] initWithField:key value:value]];
} return mutableQueryStringComponents;
} static NSString * LYPercentEscapedStringFromString(NSString *string) {
static NSString * const kLYCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kLYCharactersSubDelimitersToEncode = @"!$&'()*+,;="; NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:[kLYCharactersGeneralDelimitersToEncode stringByAppendingString:kLYCharactersSubDelimitersToEncode]]; static NSUInteger const batchSize = ; NSUInteger index = ;
NSMutableString *escaped = @"".mutableCopy; while (index < string.length) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu"
NSUInteger length = MIN(string.length - index, batchSize);
#pragma GCC diagnostic pop
NSRange range = NSMakeRange(index, length); range = [string rangeOfComposedCharacterSequencesForRange:range]; NSString *substring = [string substringWithRange:range];
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
[escaped appendString:encoded]; index += range.length;
} return escaped;
} - (NSString *)URLEncodedStringValue {
if (!self.value || [self.value isEqual:[NSNull null]]) {
return LYPercentEscapedStringFromString([self.field description]);
} else {
return [NSString stringWithFormat:@"%@=%@", LYPercentEscapedStringFromString([self.field description]), LYPercentEscapedStringFromString([self.value description])];
}
} @end

2.封装请求管理器

#import <Foundation/Foundation.h>

@interface LYHTTPRequestOperationManager : NSObject

-(void)driveTask:(nullable void(^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(nullable void (^)(NSError *__nullable error))failure; - (instancetype) initWithMethod:(NSString *)method URL:(NSString *)URL parameters:( id)parameters; @end
#import "LYHTTPRequestOperationManager.h"
#import "LYURLRequestSerialization.h" @interface LYHTTPRequestOperationManager() @property(nonatomic,strong) NSString *URL;
@property(nonatomic,strong) NSString *method;
@property(nonatomic,strong) NSDictionary *parameters;
@property(nonatomic,strong) NSMutableURLRequest *request;
@property(nonatomic,strong) NSURLSession *session;
@property(nonatomic,strong) NSURLSessionDataTask *task; @end @implementation LYHTTPRequestOperationManager - (instancetype)initWithMethod:(NSString *)method URL:(NSString *)URL parameters:(id)parameters
{
self = [super init];
if (!self) {
return nil;
}
self.URL = URL;
self.method = method;
self.parameters = parameters;
self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
self.session = [NSURLSession sharedSession];
return self;
} -(void)test{
NSLog(@"URL = %@",self.URL);
} -(void)setRequest{
if ([self.method isEqual:@"GET"]&&self.parameters.count>) { self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[[self.URL stringByAppendingString:@"?"] stringByAppendingString: [LYURLRequestSerialization LYQueryStringFromParameters:self.parameters]]]];
}
self.request.HTTPMethod = self.method; if (self.parameters.count>) {
[self.request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
}
} -(void)setBody{
if (self.parameters.count>&&![self.method isEqual:@"GET"]) { self.request.HTTPBody = [[LYURLRequestSerialization LYQueryStringFromParameters:self.parameters] dataUsingEncoding:NSUTF8StringEncoding];
}
} -(void)setTaskWithSuccess:(void(^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{
self.task = [self.session dataTaskWithRequest:self.request completionHandler:^(NSData * data,NSURLResponse *response,NSError *error){
if (error) {
failure(error);
}else{
if (success) {
success(data,response);
}
}
}];
[self.task resume];
} -(void)driveTask:(void(^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{
[self setRequest];
[self setBody];
[self setTaskWithSuccess:success failure:failure];
}
@end

3.封装适配器

#import <Foundation/Foundation.h>

@interface LyNetWork : NSObject

+(void)requestWithMethod:(nullable NSString *)method
URL:(nullable NSString *)URL
success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(nullable void (^)(NSError *__nullable error))failure; +( void)requestGetWithURL:(nullable NSString *)URL
success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(nullable void (^)(NSError *__nullable error))failure; +(void)requestGetWithURL:(nullable NSString *)URL
parameters:(nullable id) parameters
success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(nullable void (^)(NSError *__nullable error))failure; +(void)requestPostWithURL:(nullable NSString *)URL
success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(nullable void (^)(NSError *__nullable error))failure; +(void)requestPostWithURL:(nullable NSString *)URL
parameters:(nullable id) parameters
success:(nullable void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(nullable void (^)(NSError *__nullable error))failure; @end
#import "LyNetWork.h"
#import "LYURLRequestSerialization.h"
#import "LYHTTPRequestOperationManager.h" @interface LyNetWork() @end @implementation LyNetWork //+(void)requestMethod:(NSString *)method
// URL:(NSString *)URL
// parameters:(id) parameters
// success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
// failure:(void (^)(NSError *__nullable error))failure
//{
//
// LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:method URL:URL parameters:parameters];
// [manange driveTask:success failure:failure];
//} //不带parameters
+(void)requestWithMethod:(NSString *)method
URL:(NSString *)URL
success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{ LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:method URL:URL parameters:nil];
[manange driveTask:success failure:failure];
} //GET不带parameters
+(void)requestGetWithURL:(NSString *)URL
success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{ LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"GET" URL:URL parameters:nil];
[manange driveTask:success failure:failure];
}
//GET带parameters
+(void)requestGetWithURL:(NSString *)URL
parameters:(id) parameters
success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{ LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"GET" URL:URL parameters:parameters];
[manange driveTask:success failure:failure];
} //POST不带parameters
+(void)requestPostWithURL:(NSString *)URL
success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{ LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"POST" URL:URL parameters:nil];
[manange driveTask:success failure:failure];
}
//POST带parameters
+(void)requestPostWithURL:(NSString *)URL
parameters:(id) parameters
success:(void (^)(NSData *__nullable data,NSURLResponse * __nullable response))success
failure:(void (^)(NSError *__nullable error))failure
{ LYHTTPRequestOperationManager *manange = [[LYHTTPRequestOperationManager alloc] initWithMethod:@"POST" URL:URL parameters:parameters];
[manange driveTask:success failure:failure];
} @end

4.使用示例

    NSString *postURL = @"http://cityuit.sinaapp.com/p.php";
NSString *getURL= @"http://cityuit.sinaapp.com/1.php"; id parmentersPost = @{
@"username":@"",
@"password":@""
};
id parmentersGet = @{
@"value":@"Lastday",
}; [LyNetWork requestWithMethod:@"POST"
URL:@"http://cityuit.sinaapp.com/1.php?value=Lastday"
success:^(NSData *data,NSURLResponse *response){
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"requestWithMethod = %@",string);
}
failure:^(NSError *error){
NSLog(@"====%@",error);
}]; [LyNetWork requestPostWithURL:postURL
parameters:parmentersPost
success:^(NSData *data,NSURLResponse *response){
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"requestPostWithURL(带参数) = %@",string);
}
failure:^(NSError *error){ }];
[LyNetWork requestPostWithURL:postURL
success:^(NSData *data,NSURLResponse *response){
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"requestPostWithURL(不带参数) = %@",string);
}
failure:^(NSError *error){ }]; [LyNetWork requestGetWithURL:getURL
parameters:parmentersGet
success:^(NSData *data,NSURLResponse *response){
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"requestGetWithURL(带参数) = %@",string);
}
failure:^(NSError *error){ }]; [LyNetWork requestGetWithURL:getURL
success:^(NSData *data,NSURLResponse *response){
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"requestGetWithURL(不带参数) = %@",string);
}
failure:^(NSError *error){ }];

第八篇、封装NSURLSession网络请求框架的更多相关文章

  1. App 组件化/模块化之路——如何封装网络请求框架

    App 组件化/模块化之路——如何封装网络请求框架 在 App 开发中网络请求是每个开发者必备的开发库,也出现了许多优秀开源的网络请求库.例如 okhttp retrofit android-asyn ...

  2. 一步步搭建Retrofit+RxJava+MVP网络请求框架(二),个人认为这次封装比较强大了

    在前面已经初步封装了一个MVP的网络请求框架,那只是个雏形,还有很多功能不完善,现在进一步进行封装.添加了网络请求时的等待框,retrofit中添加了日志打印拦截器,添加了token拦截器,并且对Da ...

  3. Android网络请求框架

    本篇主要介绍一下Android中经常用到的网络请求框架: 客户端网络请求,就是客户端发起网络请求,经过网络框架的特殊处理,让后将请求发送的服务器,服务器根据 请求的参数,返回客户端需要的数据,经过网络 ...

  4. Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)

    最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所 ...

  5. iOS 自己封装的网络请求,json解析的类

    基本上所有的APP都会涉及网络这块,不管是用AFNetWorking还是自己写的http请求,整个网络框架的搭建很重要. 楼主封装的网络请求类,包括自己写的http请求和AFNetWorking的请求 ...

  6. 网络请求框架---Volley

    去年的Google I/O大会为android开发者带来了一个网络请求框架,它的名字叫做Volley.Volley诞生的使命就是让Android的网络请求更快,更健壮,而且它的网络通信的实现是基于Ht ...

  7. 2020,最新APP重构:网络请求框架

    在现在的app,网络请求是一个很重要的部分,app中很多部分都有或多或少的网络请求,所以在一个项目重构时,我会选择网络请求框架作为我重构的起点.在这篇文章中我所提出的架构,并不是所谓的 最好 的网络请 ...

  8. 基于Retrofit+RxJava的Android分层网络请求框架

    目前已经有不少Android客户端在使用Retrofit+RxJava实现网络请求了,相比于xUtils,Volley等网络访问框架,其具有网络访问效率高(基于OkHttp).内存占用少.代码量小以及 ...

  9. 介绍NSURLSession网络请求套件

    昨天翻译了一篇<NSURLSession的使用>的文章,地址:http://www.cnblogs.com/JackieHoo/p/4995733.html,原文是来自苹果官方介绍NSUR ...

随机推荐

  1. C# DateTime 日期加1天 减一天 加一月 减一月 等方法

    //今天 DateTime.Now.Date.ToShortDateString(); //昨天,就是今天的日期减一 DateTime.Now.AddDays(-).ToShortDateString ...

  2. 关于OPenGL和OSG的矩阵 (转)

    关于OPenGL和OSG的矩阵 矩阵真的是一个很神奇的数学工具, 虽然单纯从数学上看, 它并没有什么特别的意义, 但一旦用到空间中的坐标变换,它就“一遇风云便成龙”, 大显神威了.简单的工具实现了复杂 ...

  3. CloudStack的VO在调用setRemoved方法抛异常的原因

    今天在开发中发现一个问题,本来想对一个VO对象的removed值赋值,然后去update一下这条记录,一个最简单的set方法,但是在调用时直接抛异常了. 1: public void setRemov ...

  4. 【JavsScript】作用域链

    阿里巴巴广招前端.Java.测试.算法人才,只要你有一技之长,精通于某项领域,无学历要求,都可以来试试,有兴趣的联系luyong.sunly@alibaba-inc.com

  5. ibatis 分页的简单实现

    ibatis 物理分页的简单实现 cheungmine 2013-8-26 使用SSI (Struts2, Spring3, iBATIS2.3)框架开发Web服务的时候有一个需求就是对查询得到的结果 ...

  6. WebService究竟是什么?

    一.序言 大家或多或少都听过WebService(Web服务),有一段时间非常多计算机期刊.书籍和站点都大肆的提及和宣传WebService技术,当中不乏非常多吹嘘和做广告的成分.可是不得不承认的是W ...

  7. apt-mirror is already running(已运行)错误解决方案

    运行sudo apt-mirror却无法启动服务了.而是给出了一行错误提示信息:               apt-mirror is already running, exiting at /us ...

  8. Winform下实现图片切换特效的方法

    本文实例讲述了Winform下实现图片切换特效的方法,是应用程序开发中非常实用的一个功能.分享给大家供大家参考之用.具体方法如下: 本实例源自网络,功能较为齐全.丰富!主要功能代码如下: using ...

  9. 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏

    我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...

  10. TCP/IP协议原理与应用笔记26:网际协议(IP)之 分片(Fragmentation)

    1. 分片(Fragmentation) 适应在不同的MTU的物理网上传输. 备注: MTU:最大传输单元,Maximum Transmission Unit,它是指一种通信协议的某一层上面所能通过的 ...