解决URL中文乱码问题

在做一个HTTPS连接时, 要客户端合成一段HTTPS地址

如果地址含中文的话程序会crash, 检查发现原来是中文没有转码的原因

在NSString库里面找到了下面两个方法

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

试了下, 有效

 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结果如下

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转码两次

 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];
上一篇:SqlServer2008(R2) 数据库使用外网IP实例连接服务器


下一篇:python操作rabbitMQ小结