天天看点

网络请求的封装方法

网络请求:

Connection.h文件

#import "Connection.h"

@implementation Connection

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.data = [NSMutableData data];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

+ (void)connectionWithUrl:(NSString *)strUrl parmaters:(NSMutableDictionary *)parmaters delegate:(id<ConnectionDelegate>)delegate flag:(NSInteger)flag{
    Connection *conn = [[Connection alloc] init];
    conn.delegate = delegate;
    conn.flag = flag;
    [conn startConnectWithUrl:strUrl parmaters:parmaters];
    [conn release];
}

//网络请求的准备阶段:
- (void)startConnectWithUrl:(NSString *)strUrl parmaters:(NSMutableDictionary *)parmaters{
    //拼接网址
    NSString *str = @"";
    for (NSString *key in [parmaters allKeys]) {
        if ([str length] == 0) {
            str = [NSString stringWithFormat:@"?%@=%@",key,[parmaters objectForKey:key]];
        }else{
            str = [NSString stringWithFormat:@"%@&%@=%@",str,key,[parmaters objectForKey:key]];
        }
    }
    NSString *value = [NSString stringWithFormat:@"%@%@",strUrl,str];
    //转换字符串格式为Utf8,防止网址中出现汉字
    value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    NSURL *url = [NSURL URLWithString:value];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //网络请求的响应方法
    [request setHTTPMethod:@"GET"];
    
    //连接网络
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

//接受响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
}

//接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.data appendData:data];
}

//响应完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if ([self.delegate respondsToSelector:@selector(sendToData:flag:)]) {
        [self.delegate sendToData:self.data flag:self.flag];
    }
}

//如果出现错误显示错误信息
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"error = %@",error);
}



@end
           
#import <Foundation/Foundation.h>

@protocol ConnectionDelegate <NSObject>

//传递数据
- (void)sendToData:(NSMutableData *)data flag:(NSInteger)flag;

@end
@interface Connection : NSObject<NSURLConnectionDataDelegate>

@property(retain,nonatomic)NSMutableData *data;
@property(assign,nonatomic)NSInteger flag;
@property(assign,nonatomic)id<ConnectionDelegate>delegate;

+ (void)connectionWithUrl:(NSString *)strUrl parmaters:(NSMutableDictionary *)parmaters delegate:(id<ConnectionDelegate>)delegate flag:(NSInteger)flag;

- (void)startConnectWithUrl:(NSString *)strUrl parmaters:(NSMutableDictionary *)parmaters;

@end
           

Connection.m文件: