iOS URL編碼和URL拼接(如含中文等特殊符號(hào)).md

  • URL編碼默認(rèn)使用的字符集是US-ASCII.對(duì)于非ASCII字符, 需要使用ASCII字符集的超級(jí)進(jìn)行編碼.
  • URL中只允許包含4種字符:
英文字符 : a-zA-Z
數(shù)字: 0-9
-_.~ 4個(gè)特殊字符.
保留字符: ! * ' ( ) ; : @ & = + $ , / ? # [ ]

URL編碼使用%其后跟隨兩位(中文是三位)的十六進(jìn)制數(shù)來替換非ASCII字符,
不能在URL中包含任何非ASCII字符, 如中文字符等.

基本的NSURL

NSString *urlString = @"https://www.baidu.com";
NSURL *url = [NSURL URLWithString:urlString];

但是, 若urlString中含有中文等非URL允許的字符時(shí), 創(chuàng)建的NSURL對(duì)象為nil.

iOS 7之后: stringByAddingPercentEncodingWithAllowedCharacters

NSString *latestUrl = @"https://www.baidu.com?name=小明&age=20";

latestUrl = [[latestUrl copy] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

///https://www.baidu.com?name=%E5%B0%8F%E6%98%8E&age=20

NSString *originUrlString = @"https://www.baidu.com/百度?name=小明&age=20";
NSString *encode_fragment = [[originUrlString copy] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSCharacterSet *encode_fragment_invertedSet = [NSCharacterSet URLQueryAllowedCharacterSet].invertedSet;
NSString *encode_fragment_invertedString = [[originUrlString copy] stringByAddingPercentEncodingWithAllowedCharacters:encode_fragment_invertedSet];
/**
 encode_fragment:
 https://www.baidu.com/%E7%99%BE%E5%BA%A6?name=%E5%B0%8F%E6%98%8E&age=20
 
 encode_fragment_invertedString
 %68%74%74%70%73%3A%2F%2F%77%77%77%2E%62%61%69%64%75%2E%63%6F%6D%2F%E7%99%BE%E5%BA%A6%3F%6E%61%6D%65%3D%E5%B0%8F%E6%98%8E%26%61%67%65%3D%32%30
 */

/**

 URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}

 URLHostAllowedCharacterSet      "#%/<>?@\^`{|}

 URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}

 URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}

 URLQueryAllowedCharacterSet     "#%<>[\]^`{|}

 URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

 */

///自定義的字符集. 如(帶空格): [NSCharacterSet characterSetWithCharactersInString:@"#%/!*'\"();:@&=+$,[]? "]

NSString *latestUrl_2 = @"https://www.baidu.com?name=小明&age=20";

NSCharacterSet *defaultCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"?&=/ "];

if (defaultCharacterSet) {

    NSString *latestUrl_2_defaultAllow = [[latestUrl_2 copy] stringByAddingPercentEncodingWithAllowedCharacters:defaultCharacterSet];

    /**

     %68%74%74%70%73%3A//%77%77%77%2E%62%61%69%64%75%2E%63%6F%6D?%6E%61%6D%65=%E5%B0%8F%E6%98%8E&%61%67%65=%32%30

     可以看出除了?&=/ ,其他字符都被編碼了.

     */



    //invertSet

    NSCharacterSet *invertCharacterSet = defaultCharacterSet.invertedSet;

    latestUrl_2 = [[latestUrl_2 copy] stringByAddingPercentEncodingWithAllowedCharacters:invertCharacterSet];

    /**

     https:%2F%2Fwww.baidu.com%3Fname%3D%E5%B0%8F%E6%98%8E%26age%3D20

     */

}

/// 服務(wù)端會(huì)對(duì)請(qǐng)求進(jìn)行UTF-8解碼一次,請(qǐng)確保請(qǐng)求中的字符只進(jìn)行一次UTF-8編碼。


URL中含有中文并且拼接額外參數(shù)

NSString *originUrlString = @"https://www.baidu.com?name=小明&age=20";





//需要拼接的參數(shù):轉(zhuǎn)為通過&拼接

NSMutableDictionary *urlParamsDic = [NSMutableDictionary dictionary];

[urlParamsDic setValue:@"22" forKey:@"sex"];

[urlParamsDic setValue:@"one" forKey:@"class"];

__block NSMutableString *joinStr = [NSMutableString string];

if (urlParamsDic && [urlParamsDic isKindOfClass:[NSDictionary class]] && urlParamsDic.count) {

    

    [urlParamsDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        if (key && obj) {

            [joinStr appendFormat:@"%@=%@&",key,obj];

        }

    }];

    if ([joinStr hasSuffix:@"&"]) {

        [joinStr deleteCharactersInRange:NSMakeRange(joinStr.length-1, 1)];

    }

}

///joinStr = sex=22&class=one



/**

 *url中含有中文,先對(duì)其encode生成NSURL

 * 拼接后再decode,最后再對(duì)拼接后的encode

 */

//1.encode生成NSURL

NSURL *originUrl = [NSURL URLWithString:[originUrlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];

///originUrl = https://www.baidu.com?name=%E5%B0%8F%E6%98%8E&age=20

//2.在url后拼接參數(shù)

NSString *latestURLString = @"";

BOOL cointainQuery = NO;

if (joinStr.length == 0 || [originUrl.query rangeOfString:joinStr].location != NSNotFound) {

    //其中,若joinStr = 0則表示默認(rèn)包含該空字符串

    cointainQuery = YES;///

}



if (cointainQuery) {

    latestURLString = originUrl.absoluteString;

}else{

    ///originUrl.query: name=%E5%B0%8F%E6%98%8E&age=20

    if (originUrl.query.length>0) {

        latestURLString = [NSString stringWithFormat:@"%@&%@", originUrl.absoluteString,joinStr];

        ///https://www.baidu.com?name=%E5%B0%8F%E6%98%8E&age=20&sex=22&class=one

    }else{

        BOOL hasSuffix = [originUrl.absoluteString hasSuffix:@"?"];

        latestURLString = [NSString stringWithFormat:@"%@%@%@",originUrl.absoluteString, hasSuffix ? @"":@"?", joinStr];

    }

}

///

//3.拼接后decode

latestURLString = [latestURLString stringByRemovingPercentEncoding];

///latestURLString = https://www.baidu.com?name=小明&age=20&sex=22&class=one

///

//4.最后對(duì)對(duì)接后的encode

latestURLString =  [latestURLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

///latestURLString =https://www.baidu.com?name=%E5%B0%8F%E6%98%8E&age=20&sex=22&class=one

NSLog(@"%@",latestURLString);


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容