美文网首页
网络请求POST和GET的封装

网络请求POST和GET的封装

作者: 天涯海角我爱你 | 来源:发表于2016-06-14 20:12 被阅读127次

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];

}

相关文章

网友评论

      本文标题:网络请求POST和GET的封装

      本文链接:https://www.haomeiwen.com/subject/pzpudttx.html