step1封装post数据


	//请求地址
    NSString *url = [NSString stringWithFormat:@"%@%@", [PKConfig apiUrl], service];
    PKLog(@"请求地址是 %@",url);
	//时间戳        
    long long timestamp =  [[NSDate date] timeIntervalSince1970];
    NSString *timestampStr = [NSString stringWithFormat:@"%lld", timestamp];
    //参数
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];    
    NSData *postData = nil;    
    if(type!=1){
        // Service
        [parameters setObject:service forKey:@"service"];
        
        // ID
        [parameters setObject:timestampStr forKey:@"id"];
        
        // Common
        NSMutableDictionary *commonDict = [[NSMutableDictionary alloc] init];
        
        [commonDict setObject:@([PKConfig vc]) forKey:@"vc"];
        [commonDict setObject:[PKConfig vn] forKey:@"vn"];
        [commonDict setObject:@"1" forKey:@"build"];
        [commonDict setObject:[PKConfig uuid] forKey:@"uuid"];
        [commonDict setObject:[PKConfig imei] forKey:@"imei"];
        [commonDict setValue:[PKConfig os] forKey:@"os"];
        [commonDict setObject:[PKConfig ch] forKey:@"ch"];
        [commonDict setObject:[PKConfig osSdk] forKey:@"osSdk"];
        [commonDict setObject:[PKConfig caller] forKey:@"caller"];
        [parameters setObject:commonDict forKey:@"common"];
        
        // Param
        [parameters setObject:paramDict forKey:@"param"];
        
        // Page
        if (pageIndex > 0) {
            //NSDictionary *pageDict = @{@"index": [NSString stringWithFormat:@"%d", 1], @"count": [NSString stringWithFormat:@"%d", pageCount]};
            NSDictionary *pageDict = @{@"index": @(pageIndex), @"count": @(pageCount)};
            [parameters setObject:pageDict forKey:@"page"];
        }

封装数据如下

image

step2数据序列化并加密(这里用DES加密)


		NSError *error;
        NSData *jsonData = [[CJSONSerializer serializer] serializeObject:parameters error:&error];
        if (!error) {
            PKLog(@"json数据序列化成功");
            //加密数据
            postData = [jsonData DESEncryptByKey:[PKConfig key]];
        }

加密程序

DES_EncryptionDecryptin.h

DES_EncryptionDecryptin.m

step3请求数据(使用AFNetworking框架)


	//AFNetworking框架	
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:nil];
    //传输类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/octet-stream", @"text/html", nil];
    //请求数据封装
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    //超时设置
    if (type != 1) {
        request.timeoutInterval = 3;
    }else {
        request.timeoutInterval = 60;
    }
    //设置为POST 方法
    [request setHTTPMethod:@"POST"];
    //parameters 转json并加密后数据
    [request setHTTPBody:postData];

    //真实请求开始
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 成功后的处理
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        // 判断网络连接是否正常,如不正常,要提示
        if ([YYUtility networkStatus] == 0) {
            [UIView showNetworkDisconnectToastInKeyWindowWithPosition:ToastPositionCenter];
        }
        
    }];

step4解析回调数据

    [manager.operationQueue addOperation:operation];
    [operation waitUntilFinished];
    @try {
        if (operation.responseData) {
        	  //反回数据 并解密
            NSData *responseData = [operation.responseData DESDecryptByKey:[PKConfig key]] ;
            //判断是否有压缩,有则解压
            NSString *isgzip = [[[operation response] allHeaderFields] valueForKey:@"isgzip-based"];
            if ([isgzip isEqualToString:@"1"]) {
                responseData = [self gzipUnpack:responseData];
            }
            //转码 二进制数据转为string
            NSString *responseStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            responseStr = [responseStr stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            //解析json 返回字典
            responDict = [[responseStr objectFromJSONString] mutableCopy];
            
            PKLog(@"返回结果是:%@", responDict);
        }else{
            [responDict setObject:@"-1" forKey:@"statusCode"];
            [responDict setObject:@"unknown exception" forKey:@"statusMsg"];
        }
    }
    @catch (NSException *exception) {
        [responDict setObject:@"-1" forKey:@"statusCode"];
        [responDict setObject:@"unknown exception" forKey:@"statusMsg"];
        PKLog(@"错误原因是:%@", exception);
    }

解压缩

/**
 *  解压gzip格式的二进制包
 *  @param gzipData 待解压的gzip二进制包
 *  @return 已解压的二进制包
 */
+ (NSData *)gzipUnpack:(NSData *)gzipData
{
    if ([gzipData length] == 0) return gzipData;
    
    unsigned full_length = (uint)[gzipData length];
    unsigned half_length = (uint)[gzipData length] / 2;
    
    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length +     half_length];
    BOOL done = NO;
    int status;
    
    z_stream strm;
    strm.next_in = (Bytef *)[gzipData bytes];
    strm.avail_in = (uInt)[gzipData length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    
    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done){
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = (uint)([decompressed length] - strm.total_out);
        
        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) done = YES;
        else if (status != Z_OK) break;
    }
    if (inflateEnd (&strm) != Z_OK) return nil;
    
    // Set real length.
    if (done){
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    }
    return nil;
}

压缩解压

//self 为NSDATA
//解压
- (NSData *)gzipInflate {
    if ([self length] == 0) return self;
    
    unsigned full_length = (unsigned)[self length];
    unsigned half_length = (unsigned)[self length] / 2;
    
    NSMutableData *decompressed = [NSMutableData
                                   dataWithLength:full_length + half_length];
    BOOL done = NO;
    int status;
    
    z_stream strm;
    strm.next_in = (Bytef *)[self bytes];
    strm.avail_in = (unsigned)[self length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    
    if (inflateInit2(&strm, (15 + 32)) != Z_OK) return nil;
    while (!done) {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy:half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = (uInt)([decompressed length] - strm.total_out);
        
        // Inflate another chunk.
        status = inflate(&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) done = YES;
        else if (status != Z_OK) break;
    }
    if (inflateEnd(&strm) != Z_OK) return nil;
    
    // Set real length.
    if (done) {
        [decompressed setLength:strm.total_out];
        return [NSData dataWithData:decompressed];
    } else return nil;
}
//压缩
- (NSData *)gzipDeflate {
    if ([self length] == 0) return self;
    
    z_stream strm;
    
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.total_out = 0;
    strm.next_in = (Bytef *)[self bytes];
    strm.avail_in = (uInt)[self length];
    
    // Compresssion Levels:
    //   Z_NO_COMPRESSION
    //   Z_BEST_SPEED
    //   Z_BEST_COMPRESSION
    //   Z_DEFAULT_COMPRESSION
    
    if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15 + 16),
                     8, Z_DEFAULT_STRATEGY) != Z_OK)
        return nil;
    
    // 16K chunks for expansion
    NSMutableData *compressed = [NSMutableData dataWithLength:16384];
    
    do {
        if (strm.total_out >= [compressed length])
            [compressed increaseLengthBy:16384];
        
        strm.next_out = [compressed mutableBytes] + strm.total_out;
        strm.avail_out = (uInt)([compressed length] - strm.total_out);
        
        deflate(&strm, Z_FINISH);
    }
    while (strm.avail_out == 0);
    
    deflateEnd(&strm);
    
    [compressed setLength:strm.total_out];
    return [NSData dataWithData:compressed];
}