Urlencode和Urldecode

编码解码

920 创建: 更新: 2020/4/18 17:17 本文总阅读量

Urlencode(新)

-(NSString *)urlEncodeStr:(NSString *)orUrl {
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *encodedUrl = [orUrl stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    return encodedUrl;;
}

Urldecode(新)

-(NSString *)urlDecodeStr:(NSString *)orUrl {
    //方式 1
    NSString *decodedUrl = [orUrl stringByRemovingPercentEncoding];
    //方式 2
    //NSString *decodedUrl = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapes(NULL, (__bridge CFStringRef)orUrl, CFSTR(""));
    return decodedUrl;;
}

从url中解析参数

dp1.game.163.com/open/tomandjerrychaseasia?rees_id=1&game_id=1&game_mode=0

NSString *reesid = [self getParamByName:@"rees_id" URLString:url];  
// 获取url后拼接的参数
- (NSString *)getParamByName:(NSString *)name URLString:(NSString *)url
{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", name];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
     
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return @"";
}

Urlencode(旧)

+(NSString*)encodeString:(NSString*)unencodedString {

// CharactersToBeEscaped = @":/?&=;+!@#$()~',*";

// CharactersToLeaveUnescaped = @"[].";

NSString *encodedString = (NSString *)

CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,

(CFStringRef)unencodedString,

NULL,

(CFStringRef)@"!*'();:@&=+$,/?%#[]",

kCFStringEncodingUTF8));

return encodedString;

}

Urldecode(旧)

-(NSString *)decodeString:(NSString*)encodedString {

//NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];

NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,

(__bridge CFStringRef)encodedString,

CFSTR(""),

CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

return decodedString;