iOS9 以后的POST请求

/**
 iOS 原生数据请求

 @param url url
 @param dic 参数
 @param isPost 是否为POSt
 @param success 成功
 @param failure 失败
 */
+(void)httpByUrl:(NSString *)url
             dic:(NSDictionary *)dic
          isPost:(BOOL)isPost
         success:(void (^)(id responseObject))success
         failure:(void(^)(NSError *error))failure
{
    // 1、创建URL
    NSURL *urls = [NSURL URLWithString:url];
    
    // 2、创建请求对象
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urls];
    
    if (isPost == YES) {
        [request setHTTPMethod:@"POST"];
        NSString *send= [self dealWithParam:dic];
        // 3、设置body
        NSData *bodyData = [send dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:bodyData];
    }
    else
    {
        [request setHTTPMethod:@"GET"];
    }
    // 4、创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    // 5、创建数据请求任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data,NSURLResponse * _Nullable response,NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (error)
            {
                failure(error);
            }
            else
            {
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                if (dic)
                {
                    success(dic);
                }
                else
                {
                    failure(error);
                }
                
            }
        });
    }];
    
    // 6、启动任务
    [task resume];
    
}

// 处理字典参数
+ (NSString *)dealWithParam:(NSDictionary *)param
{
    NSArray *allkeys = [param allKeys];
    
    NSMutableString *result = [NSMutableString string];
    
    for (NSString *key in allkeys)
    {
        
        NSString *str = [NSString stringWithFormat:@"%@=%@&",key,param[key]];
        
        [result appendString:str];
    }
    
    return [result substringWithRange:NSMakeRange(0, result.length-1)];
    
}

 

你可能感兴趣的:(数据请求)