这里有很多好的答案。我的做法是:我建立了一个参数类,它负责处理配对语法以及URL编码。
#import "NSString+URLEncoding.h"
@interface UrlParameter ()
@property (strong, nonatomic) NSString *pair;
@property (strong, nonatomic) NSString *encodedPair;
@end
@implementation UrlParameter
@synthesize pair = _pair;
@synthesize encodedPair = _encodedPair;
+ (UrlParameter *)withName:(NSString *)name value:(NSString *)value {
UrlParameter *answer = [[UrlParameter alloc] init];
answer.pair = [NSString stringWithFormat:@"%@=%@", name, value];
answer.encodedPair = [NSString stringWithFormat:@"%@=%@", [name urlEncode], [value urlEncode]];
return answer;
}
@end
这依赖于我从几篇文章中整理出来的NSString类别方法。(同时支持ARC):
@implementation NSString (URLEncoding)
- (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
encoding));
}
- (NSString *)urlEncode {
return [self urlEncodeUsingEncoding:kCFStringEncodingUTF8];
}
@end
我还为URL请求创建了一个子类,并为其提供了可变参数数组,在它开始之前,执行以下操作:
@property (strong, nonatomic) NSMutableArray *parameters;
- (void)prepareParameters {
NSMutableString *encodedParameterPairs = [NSMutableString stringWithCapacity:256];
int position = 1;
for (UrlParameter *requestParameter in self.parameters) {
[encodedParameterPairs appendString:[requestParameter encodedPair]];
if (position < [self.parameters count]) [encodedParameterPairs appendString:@"&"];
position++;
}
if ([[self HTTPMethod] isEqualToString:@"GET"] || [[self HTTPMethod] isEqualToString:@"DELETE"]) {
NSString *urlString = [NSString stringWithFormat:@"%@?%@", [self URLString], encodedParameterPairs];
[self setURL:[NSURL URLWithString:urlString]];
} else {
NSData *postData = [encodedParameterPairs dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[self setHTTPBody:postData];
[self setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[self setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
}
}