IOS URL如果出现中文乱码怎么处理

来自:互联网
时间:2023-04-15
阅读:

IOS 解决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]; 

返回顶部
顶部