首页 > Web开发 > 详细

AFNetworking封装的网络请求

时间:2015-09-04 22:19:51      阅读:325      评论:0      收藏:0      [点我收藏+]
#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

 

AFNetworking封装的网络请求

原文:http://www.cnblogs.com/yang99/p/4782358.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!