非AFNetworking
- (void)requestPostPath:(NSString *)aPath bodyparams:(id)params block:(void (^)(id data, NSError *error))block {
NSMutableArray * parameters = [NSMutableArray new];
//self.requestParameter为外部传进来的参数字典
//1.遍历字典
[params enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
//2.将参数字典按照key=value的形式存放到数组中
[parameters addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
//3.创建request
NSMutableURLRequest * requst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: aPath]];
//4.设置请求方式,默认为GET
requst.HTTPMethod = @"POST";
[requst setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"contentType"];
//5.将parameters按照&拼接起来并且放到HTTPBody中,注意:此处的parameters为可变数组,
requst.HTTPBody = [[parameters componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *datdica = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
block(datdica, error);
});
}] resume];
}
被困扰之苦矣,今得矣解之,何其快哉。
网友评论