#import "AFNetworking.h" typedef void(^SuccessBlock)(AFHTTPRequestOperation * operation, id responseObj); typedef void(^FailBlock)(NSError * error, id responseObj); #import <Foundation/Foundation.h> @interface NetworkingManager : NSObject - (void)postWithURL:(NSString *)url params:(NSDictionary *)params successAction:(SuccessBlock)success failAction:(FailBlock)failure; @end
#import "NetworkingManager.h" #define BASE_URL @"http://zxxx.rimiedu.com/" @implementation NetworkingManager - (void)postWithURL:(NSString *)url params:(NSDictionary *)params successAction:(SuccessBlock)success failAction:(FailBlock)failure { // 声明一个request NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL,url]]]; // 设置请求方式POST [request setHTTPMethod:@"POST"]; // 设置请求参数,通过NSData [request setHTTPBody:[self HTTPBodyWithParams:params]]; // 通过request初始化operation AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // 设置网络请求结束后调用的block [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(operation,responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) { failure(error,operation); } NSLog(@"%@",error); }]; // 开始请求 [operation start]; } - (NSData *)HTTPBodyWithParams:(NSDictionary *)params { NSMutableArray * parameters = [NSMutableArray arrayWithCapacity:0]; [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [parameters addObject:[NSString stringWithFormat:@"%@=%@",key,obj]]; }]; NSString * paramString = [parameters componentsJoinedByString:@"&"]; NSLog(@"%@",paramString); return [paramString dataUsingEncoding:NSUTF8StringEncoding]; } //loginid=11111&passss=123123 @end
时间: 2024-12-28 10:26:47