-(void)POSTRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail { // 1. 创建请求. // 参数拼接. // 遍历参数字典,一一取出参数 NSMutableString *strM = [[NSMutableString alloc] init]; [paramaters enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { // 服务器接收参数的 key 值. NSString *paramaterKey = key; // 参数内容 NSString *paramaterValue = obj; // appendFormat :可变字符串直接拼接的方法! [strM appendFormat:@"%@=%@&",paramaterKey,paramaterValue]; }]; NSString *body = [strM substringToIndex:strM.length - 1]; NSLog(@"%@",body); NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15]; // 1.设置请求方法: request.HTTPMethod = @"POST"; // 2.设置请求体 request.HTTPBody = bodyData; // 2. 发送网络请求. // completionHandler: 说明网络请求完成! [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); // 网络请求成功: if (data && !error) { // 查看 data 是否是 JSON 数据. // JSON 解析. id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; // 如果 obj 能够解析,说明就是 JSON if (!obj) { obj = data; } // 成功回调 dispatch_async(dispatch_get_main_queue(), ^{ if (success) { success(obj,response); } }); }else //失败 { // 失败回调 if (fail) { fail(error); } } }] resume]; }
POST请求方法的封装自定义类算是粗略的完成了,接下来就是检验成果的时候:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchesBegan");
//创建参数字典
NSMutableDictionary *dict = @{@"username":@"zhangsan",@"password":@"zhang"}.mutableCopy;
// 一句话发送 GET 请求.
[[CZNetworkTool sharedNewtWorkTool] GETRequestWithUrl:@"" paramaters:dict successBlock:^(id object, NSURLResponse *response) {
NSLog(@"网络请求成功:%@",object);
} FailBlock:^(NSError *error) {
NSLog(@"网络请求失败");
}];
}
一句话发送 GET 请求.