主要功能介绍:

  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){ }];

最新文章

  1. AEAI DP V3.6.0 升级说明,开源综合应用开发平台
  2. C++:C++的两种多态形式
  3. .html(),.text()和.val()的差异总结:
  4. css设置height 100%
  5. java开发微信公众平台备忘
  6. 例题:打印正三角形。两层for循环,难点明白行与列的关系
  7. 10款实用Android UI 开发框架
  8. Java集合ArrayList的应用
  9. loadrunner:判断是否服务器连接池瓶颈
  10. HTML5 模拟现实物理效果
  11. mysql 在线加索引 锁表
  12. git修改远程仓库关联
  13. MAC 地址(单播、组播、广播地址分类)
  14. 隔离 docker 容器中的用户-------分享链接
  15. 【翻译】Chemkin - Chapter 1
  16. mysql的基本查询(等于,不等于,between...and...,)
  17. d9
  18. c sharp multithreading
  19. strongSwan配置、运行及测试
  20. 高并发中nginx较优的配置

热门文章

  1. C#综合揭秘——细说多线程
  2. [Express] Level 3: Reading from the URL
  3. PHP函数spl_autoload_register()用法和__autoload()介绍(转)
  4. linux下的ls命令
  5. LeetCode46,47 Permutations, Permutations II
  6. 3.2html学习笔记之图片
  7. 如何设计App登录模块?
  8. spring 学习总结
  9. ScrollView嵌套recyclerView出现的滑动问题
  10. error和exception的区别,RuntimeException和非RuntimeException的区别