网络请求POST和GET的封装

import <Foundation/Foundation.h>

一 声明属性和方法

// 请求数据成功之后进行回调 返回NSData

typedef void(^Finish)(NSData *data);

// 请求数据失败之后进行回调 返回NSError

typedef void(^Error)(NSError *error);

// 请求方式的枚举

typedef NS_ENUM(NSInteger,RequestType){

RequestGET,

RequestPOST

};

@interface RequestManager : NSObject

@property (nonatomic,copy)Finish finish;

@property (nonatomic,copy)Error error;

  • (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error;

import "RequestManager.h"

@implementation RequestManager

  • (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{
RequestManager *request = [[RequestManager alloc]init];


[request requestWithUrlString:urlString requestType:requestType parDic:parDic finish:finish error:error];

}

  • (void)requestWithUrlString:(NSString *)urlString requestType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(Finish)finish error:(Error)error{

    // 对block属性进行赋值

    self.finish = finish;

    self.error = error;

    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    request.timeoutInterval = 10;

    // 如果是POST请求

    if (requestType == RequestPOST) {
    [request setHTTPMethod:@"POST"];

      if (parDic.count > 0) {
          [request setHTTPBody:[self parDicToPOSTData:parDic]];
      }
    

    }

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        self.error(error);
    }
    
    else{
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.finish(data);
        });
    }
}];

//  调用此方法才是异步链接

[task resume];

}

  • (NSData *)parDicToPOSTData:(NSDictionary *)parDic{
NSMutableArray *array = [NSMutableArray array];

for (NSString *key in parDic) {
    NSString *string = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
    
    [array addObject:string];
}

NSString *postString = [array componentsJoinedByString:@"&"];

return [postString dataUsingEncoding:NSUTF8StringEncoding];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容