liwei's blog

简单功能的网络请求

在项目中,网络请求是必不可少的部分,最早的时候用过ASIHTTPRequest,到后来尝试AFNetworking,以及MKNetworkKit,关于这3个开源库网络上有很多介绍了,功能也非常丰富,但是实际上我们的应用有时候只需要简单的网络请求,不需要太多的功能,苹果自带的NSURLConnection已经能满足我们的需求了,其中

+ (void)sendAsynchronousRequest:(NSURLRequest*) request
                      queue:(NSOperationQueue*) queue
          completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler NS_AVAILABLE(10_7, 5_0);

方法已经封装的很好了,我自己参考网上的资料写了一个简单的类方法,请求的时候只需简单调用就可以满足异步请求了

先上h文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#import <Foundation/Foundation.h>
typedef enum : NSUInteger {
LWRequestMethodGet,
LWRequestMethodPost,
} LWRequestMethod;//网络请求方法
typedef void (^LWRequestCompletion)(NSDictionary *responseData, NSError *connectionError);//请求完成回调方法
@interface LWRequest : NSObject

/*
* 异步请求
* @param url 请求url
* @param params 参数
* @param method 请求类型(LWRequestMethodGet,LWRequestMethodPost)
*/

+ (void)sendAsynchronousRequestWithUrlString:(NSString *)url params:(NSDictionary *)params method:(LWRequestMethod)method completionHandler:(LWRequestCompletion) completionHandler;
@end

下面是m文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#import "LWRequest.h"
@implementation LWRequest

+ (NSString *)requestMethodName:(LWRequestMethod)method
{
switch (method) {
case LWRequestMethodGet:
return @"GET";
break;
case LWRequestMethodPost:
return @"POST";
default:
break;
}
return @"POST";
}

+(void)sendAsynchronousRequestWithUrlString:(NSString *)url params:(NSDictionary *)params method:(LWRequestMethod)method completionHandler:(LWRequestCompletion)completionHandler
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
if (params) {
NSMutableString *paramsStr = [NSMutableString stringWithCapacity:0];
NSMutableArray *paramsArr = [NSMutableArray arrayWithCapacity:0];
for (NSString *key in params) {
id value = params[key];
NSString *param = [NSString stringWithFormat:@"%@=%@", key, value];
[paramsArr addObject:param];
}
[paramsStr appendString:[paramsArr componentsJoinedByString:@"&"]];

if (method == LWRequestMethodPost) {
NSData *paramsData = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:paramsData];
}

if (method == LWRequestMethodGet) {
if ([url rangeOfString:@"?"].location != NSNotFound) {
url = [url stringByAppendingFormat:@"&%@", paramsStr];
} else {
url = [url stringByAppendingFormat:@"?%@", paramsStr];
}
}
}

url = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *req_url= [NSURL URLWithString:url];
[request setURL:req_url];

NSString *methodStr = [LWRequest requestMethodName:method];
[request setHTTPMethod:methodStr];

NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *info=[NSDictionary dictionary];
if (data) {
info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
if (completionHandler) {
completionHandler(info, connectionError);
}
}];
}
@end

在用的时候只需要引用头文件然后传递请求的SeverUrl以及参数params就可以了

[LWRequest sendAsynchronousRequestWithUrlString:SeverUrl params:params method:LWRequestMethodPost completionHandler:^( NSDictionary *responseData, NSError *connectionError) {
    NSLog(@"错误=%@",connectionError);
    if (connectionError) {
        NSLog(@"%@",connectionError );
    }
    else
    {
        NSLog(@"%@", responseData);
        // 在这里处理返回结果
    }
}];