解决URL中文乱码问题

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

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

 

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

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

试了下, 有效

 1 NSString* string1 = @"https://www.cloudsafe.com/文件夹";
 2 
 3 NSString* string2 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 4 NSString* string3 = [string2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 5 
 6 NSString* string4 = [string2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 7 NSString* string5 = [string3 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 8 
 9 NSString* string6 = [string4 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
10 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转码两次

1 NSMutableString *address = [[NSMutableString stringWithString:SetNiChengStringWithoutUserNameAndNiCheng] mutableCopy];
2     address = [[address stringByAppendingString:app.name] mutableCopy];
3     address = [[address stringByAppendingString:@"/"] mutableCopy];
4     address = [[address stringByAppendingString:_nameTextField.text] mutableCopy];
5     address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];
6     address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];

 

服务器端如何只是简单存储, 服务器接收数据后可以不用转码成中文

当客户端请求这部分数据时, 由客户端自己解码就好了

获取到字串后解码一次就可以正常显示为中文了:

1 str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

posted @ 2016-10-23 16:47  周希  阅读(1733)  评论(0编辑  收藏  举报