错误的urlencoding

时间:2013-02-04 14:39:45

标签: ios url encoding urlencode url-encoding

我有这个网址:http://google.com我用它来urlencode:

NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                        @"@" , @"&" , @"=" , @"+" ,
                        @"$" , @"," , @"[" , @"]",
                        @"#", @"!", @"'", @"(",
                        @")", @"*", nil];
NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F" , @"%3F" ,
                         @"%3A" , @"%40" , @"%26" ,
                         @"%3D" , @"%2B" , @"%24" ,
                         @"%2C" , @"%5B" , @"%5D",
                         @"%23", @"%21", @"%27",
                         @"%28", @"%29", @"%2A", nil];
int len = [escapeChars count];
NSMutableString *temp = url;
int i;
for(i = 0; i < len; i++)
{
    [temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i] withString:[replaceChars objectAtIndex:i] options:NSLiteralSearch range:NSMakeRange(0, [temp length])];
}
return temp;

这是我得到的编码字符串:http0X1.D49C41C5D49CP-5700.0000000.000000google.com

怎么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

以下是网址编码的类别:

的NSString + URLEncoding.h

#import <Foundation/Foundation.h>

@interface NSString (URLEncoding)
- (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding;
@end

的NSString + URLEncoding.m

#import "NSString+URLEncoding.h"

@implementation NSString (URLEncoding)

- (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                           (CFStringRef)self,
                                                           NULL,
                                                           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]%  ",
                                                           CFStringConvertNSStringEncodingToEncoding(encoding));
}
@end

用法:

NSString *urlText = @"http://google.com";
NSString *encodedUrlText = [urlText urlEncodeUsingEncoding:NSUTF8StringEncoding];