标签:
1.创建 NSString 分类
@interface NSString (WBRequest) - (NSString *)URLEncodedString; - (NSString *)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding; @end @implementation NSString (WBRequest) - (NSString *)URLEncodedString { return [self URLEncodedStringWithCFStringEncoding:kCFStringEncodingUTF8]; } - (NSString *)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding { return (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[self mutableCopy], NULL, CFSTR("?=,!$&‘()*+;@?\n\"<>#\t :/"), encoding)); } @end
2.将参数字典排序,并转为 GET 参数形式.
+ (NSString *)stringFromDictionaryWithApi:(NSDictionary *)dict { NSArray *sortArray=[dict allKeys]; NSArray *array = [sortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){ return [obj1 compare:obj2 options:NSNumericSearch]; }]; NSMutableArray *pairs = [NSMutableArray array]; for (int i =0; i<array.count; i++) { NSString * key =[array objectAtIndex:i]; NSString * value =[dict objectForKey:[array objectAtIndex:i]]; if ([[dict objectForKey:[array objectAtIndex:i]] isKindOfClass:[NSString class]]) { value= [value URLEncodedString]; } [pairs addObject:[NSString stringWithFormat:@"%@=%@",key,value]]; } return [pairs componentsJoinedByString:@"&"]; }
标签:
原文地址:http://www.cnblogs.com/wzyking/p/5237948.html