在做一个HTTPS连接时, 要客户端合成一段HTTPS地址
如果地址含中文的话程序会crash, 检查发现原来是中文没有转码的原因
在NSString库里面找到了下面两个方法
1
2
|
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding - (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding |
试了下, 有效
1
2
3
4
5
6
7
8
9
10
|
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-7结果如下
1
2
3
4
5
6
7
8
9
10
|
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/文件夹 |
简单说下我是如何使用的:
在合成URL后, 给整个String转码两次
1
2
3
4
5
6
|
NSMutableString *address = [[NSMutableString stringWithString:SetNiChengStringWithoutUserNameAndNiCheng] mutableCopy]; address = [[address stringByAppendingString:app.name] mutableCopy]; address = [[address stringByAppendingString:@ "/" ] mutableCopy]; address = [[address stringByAppendingString:_nameTextField.text] mutableCopy]; address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy]; address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy]; |
服务器端如何只是简单存储, 服务器接收数据后可以不用转码成中文
当客户端请求这部分数据时, 由客户端自己解码就好了
获取到字串后解码一次就可以正常显示为中文了:
str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!