需求:
在使用NSURLRequest 進(jìn)行http的網(wǎng)絡(luò)訪問的時(shí)候,如果(http://xxx.xxx.xx?xx=xx&xx=你好)請(qǐng)求參數(shù)中有中文的話抄瓦,需要對(duì)字符串進(jìn)行一次編碼瞻想,否則你使用字符串創(chuàng)建NSURL的時(shí)候爵憎,返回的是空(就是這么變態(tài))
解決方案:
1谁鳍、方法一:
對(duì)url字符串通過添加百分比編碼與允許字符集
NSString *ur = @"http://120.25.226.186:32812/login2?username=帥哥&pwd=520it&type=JSON";
NSURL *url = [NSURL URLWithString:[ur stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];//URL查詢?cè)试S的字符集
NSCharacterSet 新增枚舉
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
2鹰椒、方法二
使用字符來編碼
//第一種方式:
NSString *string = @"https://www.baidu.com/中國/iOS";
string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
NSLog(@"%@",string);
3沼死、方法三
使用utf8編碼來實(shí)現(xiàn)
NSString *string = @"https://www.baidu.com/中國/iOS";
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
輸出的結(jié)果
https://www.baidu.com/%E4%B8%AD%E5%9B%BD/iOS
解碼方式
NSString* string7 = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
輸出:https://www.baidu.com/中國/iOS
使用場景:
1着逐、ios中帶有中文字符的請(qǐng)求鏈接地址;
2意蛀、歡迎指正耸别、交流。