iOSでのurl符号化の問題
3508 ワード
NSStringのstringByAddingPercentEscapesUsingEncodingはurlパラメータを符号化することができますが、符号化が必要なすべての文字を符号化することは少し問題がありません.この機能はCFStringRefのCFURLCreateStringByAddingPercentEscapes関数によってカプセル化できる.コードは次のとおりです.
テストコード:
結果は次のとおりです.
もう1つのURL符号化&復号化の例:
出力結果:
- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
// Encode all the reserved characters, per RFC 3986
// ()
NSString *outputStr = (NSString *)
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)input,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
return outputStr;
}
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
NSMutableString *outputStr = [NSMutableString stringWithString:input];
[outputStr replaceOccurrencesOfString:@"+"
withString:@" "
options:NSLiteralSearch
range:NSMakeRange(0, [outputStr length])];
return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
テストコード:
NSString * testUrl = @"http://search.google.com?keywords=($# it's {a*123})00!*'();:@&=+$,/?%#[]";
NSLog(@"original: %@", testUrl);
NSString * encodeStr = [self encodeToPercentEscapeString:testUrl];
NSLog(@"encoded: %@", encodeStr);
NSString * encodeStr2 = [testUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"encoded2:%@", encodeStr2);
NSString * decodeStr = [self decodeFromPercentEscapeString:encodeStr];
NSLog(@"decoded: %@", decodeStr);
結果は次のとおりです.
>> original: http://search.google.com?keywords=($# it's {a*123})00!*'();:@&=+$,/?%#[]
>> encoded: http%3A%2F%2Fsearch.google.com%3Fkeywords%3D%28%24%23%20it%27s%20%7Ba%2A123%7D%2900%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D
>> encoded2: http://search.google.com?keywords=($%23%20it's%20%7Ba*123%7D)00!*'();:@&=+$,/?%25%23%5B%5D
>> decoded: http://search.google.com?keywords=($# it's {a*123})00!*'();:@&=+$,/?%#[]
もう1つのURL符号化&復号化の例:
NSString* string1 = @"https://www.cloudsafe.com/ ";
NSString* string2 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string3 = [string2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string4 = [string2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string5 = [string3 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string6 = [string4 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string7 = [string5 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
出力結果:
string1:https://www.cloudsafe.com/
string2:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9
string3:https://www.cloudsafe.com/%25E6%2596%2587%25E4%25BB%25B6%25E5%25A4%25B9
string4:https://www.cloudsafe.com/
string5:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9
string6:https://www.cloudsafe.com/
string7:https://www.cloudsafe.com/