-
Notifications
You must be signed in to change notification settings - Fork 1
/
NSURLRequest+na.m
57 lines (53 loc) · 1.86 KB
/
NSURLRequest+na.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
//
// NSURLRequest+na.m
// na_ios_test
//
// Created by nashibao on 2012/11/05.
// Copyright (c) 2012年 nashibao. All rights reserved.
//
#import "NSURLRequest+na.h"
@implementation NSURLRequest (na)
+ (NSURLRequest *)request:(NSString *)baseURL query:(NSDictionary *)query protocol:(NANetworkProtocol)protocol encoding:(NSStringEncoding)encoding{
NSString *urlstring = [baseURL stringByAddingPercentEscapesUsingEncoding:encoding];
NSMutableString *requestString = [[NSMutableString alloc] init];
NSString *method = @"GET";
switch (protocol) {
case NANetworkProtocolGET:
method = @"GET";
break;
case NANetworkProtocolPOST:
method = @"POST";
break;
case NANetworkProtocolPUT:
method = @"PUT";
break;
case NANetworkProtocolDELETE:
method = @"DELETE";
break;
default:
break;
}
NSData *requestData = nil;
if([query count] > 0){
for(NSString *key in query){
id val = query[key];
if([val isKindOfClass:[NSString class]]){
val = [val encodeURIComponentByEncoding:encoding];
}
[requestString appendFormat:@"%@=%@&", key, val];
}
if (protocol==NANetworkProtocolGET){
urlstring = [NSString stringWithFormat:@"%@?%@", urlstring, requestString];
}else{
requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding];
}
}
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlstring]];
if(requestData)
[req setHTTPBody:requestData];
[req setHTTPMethod: method];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
//gNSLog(@"%s|%@|%@", __PRETTY_FUNCTION__, urlstring, query);
return req;
}
@end