网络请求

//.h文件
/**
 * 因为项目中几乎每个地方都用到了网络请求 所以可以把网络请求封装一个模块出来
 *(多个地方用到的某个功能 都可以单独抽出来抽出来 做个功能模块)  <封装>
 *
 */


#import <Foundation/Foundation.h>

//声明一个 blcok 属性 用来传值
//finishBlcok 把请求完毕 解析好的数据传出来  id 可以代表任意类型
//解析为系统的 json 解析   现在外面一般基本全是json

typedef void (^FinishBlock)(id dataResponse);



@interface PKTRequestManager : NSObject<NSURLConnectionDelegate>

@property (strong, nonatomic) NSMutableData *resultData;

@property (nonatomic, strong)FinishBlock finishBlock;


/**
 *  post 类方法
 *
 *  @param urlStr    接口参数  内部设计了接口基本链接的宏 只传后面跟的接口参数
 *  @param paramters 需要传的参数
 *  @param block     返回值
 */
+ (void)postRequestWithURL:(NSString *)urlStr
                 paramters:(NSDictionary *)paramters
              finshedBlock:(FinishBlock)block;

@end

//.m文件
#import "PKTRequestManager.h"
#import "APIHeader.h"

//宏
//接口基本链接


@implementation PKTRequestManager


//实现方法
+ (void)postRequestWithURL:(NSString *)urlStr
                 paramters:(NSDictionary *)paramters
              finshedBlock:(FinishBlock)block{

    
    PKTRequestManager *requestManager =[PKTRequestManager new];

    requestManager.finishBlock = block;
    //拼接接口
    NSString *str =[NSString stringWithFormat:@"%@%@",PKAPI,urlStr];
    //转化 url
    NSURL *url = [NSURL URLWithString:str];
    
    //使用 NSMutableURLRequest 创建对象
    //NSURLRequest 是一个不可变的请求,默认执行的就是GET请求。也就是说,通过NSURLRequest无法指定 请求方式为 POST,因为TA是不可变的。
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    

    [request setHTTPMethod:@"POST"];
    
    //准备发送的字符串
    NSString *postStr = @"";
    //取出post参数中所有key
    NSArray *keyArray = [paramters allKeys];
    //遍历 拼接参数的字符串
    for (NSString *keyString in keyArray) {
        
        postStr = [NSString stringWithFormat:@"%@&%@=%@",postStr,keyString,[paramters objectForKey:keyString]];
        
    }
    
    [request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    //发出请求
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:requestManager];
    NSLog(connection ? @"网络连接创建成功" : @"网络连接连接创建失败");

}

/**
 *  接收到服务器回应的时回调
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //强转 ???
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if (!self.resultData) {
        self.resultData = [[NSMutableData alloc]init];
    } else {
        [self.resultData setLength:0]; ///?? 彻底释放内存 如果存在做清零处理
    }
    
    if ([response respondsToSelector:@selector(allHeaderFields)]) {
        // 取得所有的请求的头
        NSDictionary *dic = [httpResponse allHeaderFields];
        NSLog(@"network---Header:%@",[dic description]);
    }
}
/**
 *  接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.resultData appendData:data];
}
/**
 *  数据传完之后调用此方法
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSError *error;
    //???下面  泛型接受 字典 或者数组
    id dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        NSLog(@"解析错误");
        self.finishBlock(nil);
    }
    
    if (self.finishBlock) {
        self.finishBlock(dic);
    }
}
/**
 *  网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"network error : %@", [error localizedDescription]);
    
    if (self.finishBlock) {
        self.finishBlock(nil);
    }
}


@end
 posted on 2015-06-03 01:36  ianhao_cn  阅读(424)  评论(0编辑  收藏  举报